How to remove a key from a Python dictionary?

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

    If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and Pythonic readable:

    myDict = {'a':1,'b':2,'c':3,'d':4}
    map(myDict.pop, ['a','c']) # The list of keys to remove
    >>> myDict
    {'b': 2, 'd': 4}
    

    And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:

    map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
    [1, 3, None] # pop returns
    >>> myDict
    {'b': 2, 'd': 4}
    

    or in python3, you must use a list comprehension instead:

    [myDict.pop(x, None) for x in ['a', 'c', 'e']]
    

    It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.

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