How to remove a key from a Python dictionary?

2019-01-01 01:41发布

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?

8条回答
旧人旧事旧时光
2楼-- · 2019-01-01 02:04

It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I'll add this as an answer to save others googling time:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised

Documentation

查看更多
看风景的人
3楼-- · 2019-01-01 02:07

Using the "del" keyword:

del dict[key]
查看更多
登录 后发表回答