Tony Tony - 4 months ago 9
Python Question

How to remove a key from a 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?

Answer

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.