简体   繁体   English

从 Python 字典中删除多个键

[英]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}

Remove a number of keys删除一些键

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 次迭代的结果:

  1. 1.88s 1.9 ns/iter (100%) 1.88 秒 1.9 纳秒/迭代 (100%)
  2. 2.41s 2.4 ns/iter (128%) 2.41 秒 2.4 纳秒/迭代 (128%)
  3. 4.15s 4.2 ns/iter (221%) 4.15 秒 4.2 纳秒/迭代 (221%)

So del is the fastest.所以del是最快的。

Remove a number of keys safely安全地移除一些钥匙

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}
  1. 2.03s 2.0 ns/iter (100%) 2.03s 2.0 ns/iter (100%)
  2. 2.38s 2.4 ns/iter (117%) 2.38 秒 2.4 纳秒/迭代 (117%)
  3. 4.11s 4.1 ns/iter (202%) 4.11 秒 4.1 纳秒/迭代 (202%)

Still, del is the fastest.尽管如此, del是最快的。

The general form I use is this:我使用的一般形式是这样的:

  1. Produce a list of keys to delete from the mapping;生成要从映射中删除的键列表;
  2. Loop over the list and call del for each.循环遍历列表并为每个调用del

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM