从字典中删除一个项目 [英] Delete an item from a dictionary

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

问题描述



我知道我可以调用 .pop ,但返回删除的项目。我正在寻找的是返回字典减去所涉及的元素。



目前我有一个帮助函数接受有问题的字典作为参数,然后返回一个字典,删除项目,是否有更优雅的解决方案? p>

解决方案

del 语句删除元素:

  del d [key] 

但是,这会使现有的字典发生变化,所以内容任何其他人引用同一个实例的字典更改。要返回一个新的字典,请复制一个字典:

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

dict()构造函数使浅拷贝。要深入复制,请参阅 复制模块


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.

这篇关于从字典中删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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