When trying to delete a key from a dictionary, I write:
if 'key' in myDict:
del myDict['key']
Is there a one line way of doing this?
转载于:https://stackoverflow.com/questions/11277432/how-to-remove-a-key-from-a-python-dictionary
When trying to delete a key from a dictionary, I write:
if 'key' in myDict:
del myDict['key']
Is there a one line way of doing this?
转载于:https://stackoverflow.com/questions/11277432/how-to-remove-a-key-from-a-python-dictionary
Use dict.pop()
:
my_dict.pop('key', None)
This will return my_dict[key]
if key
exists in the dictionary, and None
otherwise. If the second parameter is not specified (ie. my_dict.pop('key')
) and key
does not exist, a KeyError
is raised.