如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
当前回答
>>> def delete_key(dict, key):
... del dict[key]
... return dict
...
>>> test_dict = {'one': 1, 'two' : 2}
>>> print delete_key(test_dict, 'two')
{'one': 1}
>>>
这不做任何错误处理,它假设密钥在dict中,您可能需要先检查它,如果没有,则引发
其他回答
我认为你的解决方案是最好的方法。但如果你想要另一个解决方案,你可以使用旧字典中的关键字创建一个新字典,而不包括你指定的关键字,如下所示:
>>> 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'}
del陈述就是你要找的。如果您有一个名为foo的字典,其键名为“bar”,则可以像这样从foo中删除“bar”:
del foo['bar']
请注意,这将永久修改正在操作的词典。如果您想保留原始词典,则必须事先创建一个副本:
>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}
dict调用生成一个浅显的副本。如果需要深度复制,请使用copy.depcopy。
为了方便,您可以复制并粘贴以下方法:
def minus_key(key, dictionary):
shallow_copy = dict(dictionary)
del shallow_copy[key]
return shallow_copy
在Python 3中,“dict”对象没有属性“remove”。
但使用immutables包,可以执行允许对Map对象应用更改并创建新的(派生的)Maps的突变:
import immutables
map = immutables.Map(a=1, b=2)
map1 = map.delete('b')
print(map, map1)
# will print:
# <immutables.Map({'b': 2, 'a': 1})>
# <immutables.Map({'a': 1})>
使用del可以删除传递该值键的dict值
链接:德尔法
del dictionary['key_to_del']
解决方案1:删除
info = {'country': 'Iran'}
country = info.pop('country') if 'country' in info else None
解决方案2:不删除
info = {'country': 'Iran'}
country = info.get('country') or None