如何从Python字典中删除键? [英] How can I remove a key from a Python dictionary?
本文介绍了如何从Python字典中删除键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从字典中删除键时,我使用:
When deleting a key from a dictionary, I use:
if 'key' in my_dict:
del my_dict['key']
有没有一种方法可以做到这一点?
Is there a one line way of doing this?
推荐答案
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop()
:
my_dict.pop('key', None)
如果字典中存在 key
,它将返回 my_dict [key]
,否则返回 None
.如果未指定第二个参数(即 my_dict.pop('key')
)并且 key
不存在,则会引发 KeyError
This will return my_dict[key]
if key
exists in the dictionary, and None
otherwise. If the second parameter is not specified (ie. my_dict.pop('key')
) and key
does not exist, a KeyError
is raised.
要删除肯定存在的密钥,您也可以使用
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
如果密钥不在词典中,则会引发 KeyError
.
This will raise a KeyError
if the key is not in the dictionary.
这篇关于如何从Python字典中删除键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文