How to remove a key from a Python dictionary?

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

    Specifically to answer "is there a one line way of doing this?"

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

    ...well, you asked ;-)

    You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of

    try:
        del my_dict['key']
    except KeyError:
        pass
    

    which, of course, is definitely not a one-liner.

提交回复
热议问题