如何从python字典中删除一个键? [英] How to remove a key from a python dictionary?

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

问题描述

当尝试从字典中删除一个键时,我写道:

When trying to delete a key from a dictionary, I write:

if 'key' in myDict:
    del myDict['key']

有没有一种方式这样做? >

Is there a one line way of doing this?

推荐答案

使用 dict.pop()

my_dict.pop('key', None)

这将返回 my_dict [key] 如果存在于字典中,而否则。如果没有指定第二个参数(即 my_dict.pop('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.

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

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