如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
当前回答
我认为你的解决方案是最好的方法。但如果你想要另一个解决方案,你可以使用旧字典中的关键字创建一个新字典,而不包括你指定的关键字,如下所示:
>>> 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'}
其他回答
下面的代码片段肯定会帮助您,我在每行中都添加了注释,这将帮助您理解代码。
def execute():
dic = {'a':1,'b':2}
dic2 = remove_key_from_dict(dic, 'b')
print(dict2) # {'a': 1}
print(dict) # {'a':1,'b':2}
def remove_key_from_dict(dictionary_to_use, key_to_delete):
copy_of_dict = dict(dictionary_to_use) # creating clone/copy of the dictionary
if key_to_delete in copy_of_dict : # checking given key is present in the dictionary
del copy_of_dict [key_to_delete] # deleting the key from the dictionary
return copy_of_dict # returning the final dictionary
或者也可以使用dict.pop()
d = {"a": 1, "b": 2}
res = d.pop("c") # No `KeyError` here
print (res) # this line will not execute
或者更好的方法是
res = d.pop("c", "key not found")
print (res) # key not found
print (d) # {"a": 1, "b": 2}
res = d.pop("b", "key not found")
print (res) # 2
print (d) # {"a": 1}
>>> 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中,您可能需要先检查它,如果没有,则引发
在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语句删除一个元素:
del d[key]
请注意,这会改变现有的字典,因此字典的内容会对任何引用同一实例的其他人发生变化。要返回新词典,请复制词典:
def removekey(d, key):
r = dict(d)
del r[key]
return r
dict()构造函数生成一个浅副本。要进行深度复制,请参阅复制模块。
注意,为每个dict del/assignment等制作一份副本。意味着你将从恒定时间变为线性时间,同时也使用线性空间。对于小字典来说,这不是问题。但是,如果您计划制作大量大型字典的副本,您可能需要一种不同的数据结构,如HAMT(如本答案所述)。
使用del可以删除传递该值键的dict值
链接:德尔法
del dictionary['key_to_del']