How to remove a key from a Python dictionary?

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

    You can use exception handling if you want to be very verbose:

    try: 
        del dict[key]
    
    except KeyError: pass
    

    This is slower, however, than the pop() method, if the key doesn't exist.

    my_dict.pop('key', None)
    

    It won't matter for a few keys, but if you're doing this repeatedly, then the latter method is a better bet.

    The fastest approach is this:

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

    But this method is dangerous because if 'key' is removed in between the two lines, a KeyError will be raised.

提交回复
热议问题