How to remove a key from a Python dictionary?

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

提交回复
热议问题