Delete an item from a dictionary

Is there a way to delete an item from a dictionary in Python?

I know I can just call .pop on the dictionary, but that returns the item that was removed. What I'm looking for is something returns the dictionary minus the element in question.

At present I have a helper function that accepts the dictionary in question as parameter, and then returns a dictionary with the item removed, Is there a more elegant solution?


The del statement removes an element:

del d[key]

However, this mutates the existing dictionary so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:

def removekey(d, key):
    r = dict(d)
    del r[key]
    return r

The dict() constructor makes a shallow copy. To make a deep copy, see the copy module.


pop mutates the dictionary.

 >>>lol = {"hello":"gdbye"}
 >>>lol.pop("hello")
    'gdbye'
 >>> lol
     {}

If you want to keep the original you could just copy it.


I think your solution is best way to do it. But if you want another solution, you can create a new dictionary with using the keys from old dictionary without including your specified key, like this:

>>> a
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> {i:a[i] for i in a if i!=0}
{1: 'one', 2: 'two', 3: 'three'}
链接地址: http://www.djcxy.com/p/9404.html

上一篇: 在Python中如何通过字符串调用模块和函数?

下一篇: 从字典中删除项目