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?
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.