How to remove a key from a Python dictionary?

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

    del my_dict[key] is slightly faster than my_dict.pop(key) for removing a key from a dictionary when the key exists

    >>> import timeit
    >>> setup = "d = {i: i for i in range(100000)}"
    
    >>> timeit.timeit("del d[3]", setup=setup, number=1)
    1.79e-06
    >>> timeit.timeit("d.pop(3)", setup=setup, number=1)
    2.09e-06
    >>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
    0.00786
    

    But when the key doesn't exist if key in my_dict: del my_dict[key] is slightly faster than my_dict.pop(key, None). Both are at least three times faster than del in a try/except statement:

    >>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
    0.0229
    >>> timeit.timeit("d.pop('missing key', None)", setup=setup)
    0.0426
    >>> try_except = """
    ... try:
    ...     del d['missing key']
    ... except KeyError:
    ...     pass
    ... """
    >>> timeit.timeit(try_except, setup=setup)
    0.133
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 13:07

    Another way is by Using items() + dict comprehension

    items() coupled with dict comprehension can also help us achieve task of key-value pair deletion but, it has drawback of not being an inplace dict technique. Actually a new dict if created except for the key we don’t wish to include.

    test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21} 
    
    # Printing dictionary before removal 
    print ("dictionary before performing remove is : " + str(test_dict)) 
    
    # Using items() + dict comprehension to remove a dict. pair 
    # removes  vinod
    new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'} 
    
    # Printing dictionary after removal 
    print ("dictionary after remove is : " + str(new_dict)) 
    

    Output:

    dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
    dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题