当某项的键未知时,从字典中删除该项

通过值从字典中删除一个条目的最佳方法是什么,也就是说,当该条目的键是未知的时候?这里有一个简单的方法:

for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]

有更好的方法吗? 在迭代时从字典中变异(删除条目)有什么错吗?

231560 次浏览

Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as

some_dict = {key: value for key, value in some_dict.items()
if value is not value_to_remove}

But this may not do what you want:

>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}

所以你可能需要 !=而不是 is not

items()返回一个列表,而您正在迭代的正是这个列表,因此在这里改变循环中的 dict 并不重要。如果您使用的是 iteritems(),那么在循环 would be problematic中修改 dict,在 Python 2.7中修改 viewitems()也是如此。

我想不出一个更好的方法来删除从价值判决的项目。

正如您所建议的那样,在迭代时从字典中删除项目并没有什么错。小心多个线程同时使用同一个字典,这可能会导致 KeyError 或其他问题。

当然,在 http://docs.python.org/library/stdtypes.html#typesmapping看医生

dict.pop(key[, default])方法允许您在知道键时删除项。如果它移除该项,则返回键处的值,否则返回作为 default传递的值。见 那些文件。'

例如:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']

我会建立一个需要删除的键的列表,然后删除它们。它简单、高效,并且避免了同时迭代和更改 dict 的任何问题。

keys_to_remove = [key for key, value in some_dict.iteritems()
if value == value_to_remove]
for key in keys_to_remove:
del some_dict[key]

Del的简单比较:

import timeit
code = """
results = {'A': 1, 'B': 2, 'C': 3}
del results['A']
del results['B']
"""
print timeit.timeit(code, number=100000)
code = """
results = {'A': 1, 'B': 2, 'C': 3}
results.pop('A')
results.pop('B')
"""
print timeit.timeit(code, number=100000)

结果:

0.0329667857143
0.0451040902256

所以 Del快。

y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]

C 是新字典,a 是原始字典{‘ z’,‘ w’} 是要从

c = {key:a[key] for key in a.keys() - {'z', 'w'}}

检查 https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html

我就是这么做的。

for key in some_dict.keys():
if some_dict[key] == item_to_remove:
some_dict.pop(key)
break