I want to remove a key from a dictionary if it is present. I currently use this code:
if key in my_dict:
del my_dict[key]
Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?
See Delete an element from a dictionary for more general approaches to the problem of removing a key from a dict (including ones which produce a modified copy).
To delete a key regardless of whether it is in the dictionary, use the two-argument form of
dict.pop():This will return
my_dict[key]ifkeyexists in the dictionary, andNoneotherwise. If the second parameter is not specified (i.e.my_dict.pop('key')) andkeydoes not exist, aKeyErroris raised.To delete a key that is guaranteed to exist, you can also use
This will raise a
KeyErrorif the key is not in the dictionary.