Python 如果键存在,则删除字典项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15411107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:02:59  来源:igfitidea点击:

Delete a dictionary item if the key exists

pythonpython-2.7

提问by Simon Hughes

Is there any other way to delete an item in a dictionary only if the given key exists, other than:

仅当给定的键存在时,是否还有其他方法可以删除字典中的项目,除了:

if key in mydict:
    del mydict[key]

The scenario is that I'm given a collection of keys to be removed from a given dictionary, but I am not certain if all of them exist in the dictionary. Just in case I miss a more efficient solution.

场景是我得到了一组要从给定字典中删除的键,但我不确定字典中是否存在所有键。以防万一我错过了更有效的解决方案。

采纳答案by Adem ?zta?

You can use dict.pop:

您可以使用:dict.pop

 mydict.pop("key", None)

Note that if the second argument, i.e. Noneis not given, KeyErroris raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

请注意,如果None没有给出第二个参数,即KeyError如果键不在字典中,则会引发。提供第二个参数可以防止条件异常。

回答by mgilson

There is also:

还有:

try:
    del mydict[key]
except KeyError:
    pass

This only does 1 lookup instead of 2. However, exceptclauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.

这只会执行 1 次查找,而不是 2 次。但是,except子句的开销很大,因此如果您最终经常使用 except 子句,这可能会比您已有的效率低。

回答by hughdbrown

Approach: calculate keys to remove, mutate dict

方法:计算要删除的键,变异 dict

Let's call keysthe list/iterator of keys that you are given to remove. I'd do this:

让我们调用keys您要删除的键的列表/迭代器。我会这样做:

keys_to_remove = set(keys).intersection(set(mydict.keys()))
for key in keys_to_remove:
    del mydict[key]

You calculate up front all the affected items and operate on them.

您预先计算所有受影响的项目并对其进行操作。

Approach: calculate keys to keep, make new dict with those keys

方法:计算要保留的键,用这些键创建新的字典

I prefer to create a new dictionary over mutating an existing one, so I would probably also consider this:

我更喜欢创建一个新的字典而不是改变一个现有的字典,所以我可能也会考虑这个:

keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: v for k, v in mydict.iteritems() if k in keys_to_keep}

or:

或者:

keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: mydict[k] for k in keys_to_keep}