[英]Remove more than one key from Python dict
Is there any efficient shortcut method to delete more than one key at a time from a python dictionary?是否有任何有效的快捷方法可以一次从 python 字典中删除多个键?
For instance;例如;
x = {'a': 5, 'b': 2, 'c': 3}
x.pop('a', 'b')
print x
{'c': 3}
Use the del
statement :使用
del
语句:
x = {'a': 5, 'b': 2, 'c': 3}
del x['a'], x['b']
print x
{'c': 3}
I have tested the performance of three methods:我测试了三种方法的性能:
d = dict.fromkeys('abcdefghijklmnopqrstuvwxyz')
remove_keys = set('abcdef')
# Method 1
for key in remove_keys:
del d[key]
# Method 2
for key in remove_keys:
d.pop(key)
# Method 3
{key: v for key, v in d.items() if key no in remove_keys}
Here are the results of 1M iterations:以下是 1M 次迭代的结果:
So del
is the fastest.所以
del
是最快的。
However, if you want to delete safely , so that it does not fail with KeyError, you have to modify the code:但是,如果要安全删除 ,使其不会因 KeyError 而失败,则必须修改代码:
# Method 1
for key in remove_keys:
if key in d:
del d[key]
# Method 2
for key in remove_keys:
d.pop(key, None)
# Method 3
{key: v for key, v in d.items() if key no in remove_keys}
Still, del
is the fastest.尽管如此,
del
是最快的。
The general form I use is this:我使用的一般形式是这样的:
Example:例子:
Say I want to delete all the string keys in a mapping.假设我想删除映射中的所有字符串键。 Produce a list of them:
生成它们的列表:
>>> x={'a':5,'b':2,'c':3,1:'abc',2:'efg',3:'xyz'}
>>> [k for k in x if type(k) == str]
['a', 'c', 'b']
Now I can delete those:现在我可以删除那些:
>>> for key in [k for k in x if type(k) == str]: del x[key]
>>> x
{1: 'abc', 2: 'efg', 3: 'xyz'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.