从字典中删除元素 [英] Delete an element from a dictionary

查看:128
本文介绍了从字典中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用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]

但是,这会使现有字典发生突变,因此对于引用同一实例的其他任何人,字典的内容都会更改.要返回 new 词典,请复制该词典:

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

dict()构造函数创建一个浅拷贝.要进行深层复制,请参见 copy模块.

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

请注意,为每个字典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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆