How to remove a key from a Python dictionary?

后端 未结 13 1837
-上瘾入骨i
-上瘾入骨i 2020-11-22 12:37

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?

13条回答
  •  广开言路
    2020-11-22 13:10

    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

提交回复
热议问题