如何从 Python 字典中删除键? [英] How can I remove a key from a Python dictionary?

查看:51
本文介绍了如何从 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?

推荐答案

要删除一个键而不管它是否在字典中,请使用 dict.pop():

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 (i.e. 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屋!

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