简体   繁体   English

从python字典中删除某些前缀的键的有效方法

[英]Efficient way of removing keys of certain prefix from python dictionary

I have a python dictionary which looks something like this; 我有一个python字典,看起来像这样;

{'Prefix_1':'12', 'Prefix_2':'11', 'Prefix_3':'14', '1':'241', '2':'312', '3':'421'
}

I want to remove the key-value pairs of those with keys that start with 'Prefix'. 我想删除那些带有以'Prefix'开头的键的键值对。 The result should be a dictionary that look like this; 结果应该是一个看起来像这样的字典;

{'1':'241', '2':'312', '3':'421'
}

My current way of doing so is to remove each pair one by one by using del dictionary['Prefix_X'] . 我目前这样做的方法是使用del dictionary['Prefix_X']逐个删除每一对。 What are more efficient ways of doing so? 有什么更有效的方法呢?

I am using python 2.7 我正在使用python 2.7

Since the other answers all use dict comprehension to create a new dict and leave the original dict untouched, I'll give one that change the dict in place: 由于其他答案都使用dict理解来创建一个新的dict并且保持原始dict不变,我将给出一个改变dict的地方:

for k in d.keys():
    if k.startswith('Prefix'):
        d.pop(k)

Is there a better way? 有没有更好的办法?

Let's say there are N keys in the dictionary, to find all keys with the given prefix, you'll have to iterate over all the keys, and this is of O(N) time complexity. 假设字典中有N个键,要查找具有给定前缀的所有键,您必须迭代所有键,这具有O(N)时间复杂度。

Then you'll need to delete them one by one, in the worst case all of them are with the given prefix, so this is also of O(N) time complexity. 然后你需要逐个删除它们,在最坏的情况下,所有这些都使用给定的前缀,所以这也是O(N)时间复杂度。

The total time complexity if O(N). O(N)的总时间复杂度。

You could use a dict comprehension over the original dictionary: 您可以对原始字典使用字典理解:

D = {'Prefix_1':'12', 'Prefix_2':'11', 'Prefix_3':'14', '1':'241', '2':'312', '3':'421'

NewDict = {k: D[k] for k in D if not k.startswith('Prefix')}
NewDict
{'2': '312', '3': '421', '1': '241'}

use dictionary comprehensions 使用字典理解

{k:v for k, v in d.items() if not k.startswith('Prefix')}

In [44]: {k:v for k, v in d.items() if not k.startswith('Prefix')}
Out[44]: {'1': '241', '2': '312', '3': '421'}
>>> z = {'Prefix_1':'12', 'Prefix_2':'11', 'Prefix_3':'14', '1':'241', '2':'312', '3':'421'}
>>> {k:v for k,v in z.items() if not k.startswith('Prefix')}
{'1': '241', '3': '421', '2': '312'}
d1 = {'Prefix_1':'12', 'Prefix_2':'11', 'Prefix_3':'14', '1':'241', '2':'312', '3':'421'}
d2 = {k: v for k, v in d1.iteritems() if not k.startswith('Prefix')}

print d1
print d2

Try to this. 试试这个。

for key in d.keys():
    if 'Prefix' in key:
        d.pop(key)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM