从字典中删除一个元素 [英] Delete an element from a dictionary
问题描述
有没有办法在 Python 中从字典中删除项目?
Is there a way to delete an item from a dictionary in Python?
另外,如何从字典中删除一个项目以返回副本(即不修改原始项目)?
Additionally, how can I delete an item from a dictionary to return a copy (i.e., not modifying the original)?
推荐答案
del
语句 删除一个元素:
The del
statement removes an element:
del d[key]
请注意,这会改变现有字典,因此对于引用同一实例的任何其他人,字典的内容都会更改.要返回新字典,请复制字典:
Note that 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
dict()
构造函数创建一个浅拷贝.要进行深层复制,请参阅copy
模块.
The dict()
constructor makes a shallow copy. To make a deep copy, see the copy
module.
请注意,为每个 dict del
/assignment/etc 制作一个副本.意味着您将从恒定时间变为线性时间,并且还使用线性空间.对于小字典,这不是问题.但是,如果您打算制作大量大型字典的副本,您可能需要不同的数据结构,例如 HAMT(如 中所述)这个答案).
Note that making a copy for every dict del
/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).
这篇关于从字典中删除一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!