从Python dict中删除多个键

时间:2011-12-09 16:02:45

标签: python dictionary

是否有任何有效的快捷方法可以从python词典中一次删除多个键?

例如;

x = {'a': 5, 'b': 2, 'c': 3}
x.pop('a', 'b')
print x
{'c': 3}

3 个答案:

答案 0 :(得分:13)

使用the del statement

x = {'a': 5, 'b': 2, 'c': 3}
del x['a'], x['b']
print x
{'c': 3}

答案 1 :(得分:2)

我使用的一般形式是:

  1. 生成要从映射中删除的键列表;
  2. 循环列表并为每个人致电del
  3. 示例:

    假设我要删除映射中的所有字符串键。制作一份清单:

    >>> 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'}
    

答案 2 :(得分:2)

删除许多键

我已经测试了三种方法的性能:

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}

这是一百万次迭代的结果:

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

所以del是最快的。

安全地删除许多键

但是,如果要安全删除 ,以免因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. 2.38s 2.4 ns / iter(117%)
  3. 4.11s 4.1 ns / iter(202%)

还是,del是最快的。