从字典中安全删除多个键 [英] Removing multiple keys from a dictionary safely
本文介绍了从字典中安全删除多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果d.has_key('key'):
del d ['key']
但是,我需要安全地从字典中删除多个条目。我正在想定义一个元组中的条目,因为我将需要多次执行此操作。
entitiesToREmove =('a ','b','c')
for entitiesToRemove:
如果d.has_key(x):
del d [x]
但是,我想知道是否有更聪明的方式来执行此操作?
解决方案
为什么不这样:
entries =('a','b' c')
the_dict = {'b':'foo'}
def entries_to_remove(entries,the_dict):
条目中的键值:
如果键入the_dict:
del the_dict [key]
I know to remove an entry, 'key' from my dictionary d
, safely, you do:
if d.has_key('key'):
del d['key']
However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once.
entitiesToREmove = ('a', 'b', 'c')
for x in entitiesToRemove:
if d.has_key(x):
del d[x]
However, I was wondering if there is a smarter way to do this?
解决方案
Why not like this:
entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}
def entries_to_remove(entries, the_dict):
for key in entries:
if key in the_dict:
del the_dict[key]
这篇关于从字典中安全删除多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文