How to remove a key from a Python dictionary?

后端 未结 13 1489
-上瘾入骨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:09

    You can use a dictionary comprehension to create a new dictionary with that key removed:

    >>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}
    

    You can delete by conditions. No error if key doesn't exist.

提交回复
热议问题