有没有一种高效的快捷方法可以从Python字典中一次性删除多个键?
例如:
例如:
x = {'a': 5, 'b': 2, 'c': 3}
x.pop('a', 'b')
print x
{'c': 3}
x = {'a': 5, 'b': 2, 'c': 3}
x.pop('a', 'b')
print x
{'c': 3}
使用del
语句:
x = {'a': 5, 'b': 2, 'c': 3}
del x['a'], x['b']
print x
{'c': 3}
我已经测试了三种方法的性能:
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}
del
是最快的。# 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}
不过,del
是最快的。
我通常使用以下一般形式:
示例:
假设我想要从映射中删除所有字符串键。生成该键的列表:
>>> 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']
>>> for key in [k for k in x if type(k) == str]: del x[key]
>>> x
{1: 'abc', 2: 'efg', 3: 'xyz'}