Is there any other way to delete an item in a dictionary only if the given key exists, other than:
if key in mydict:
del mydict[key]
The scenario is that I'm given a collection of keys to be removed from a given dictionary, but I am not certain if all of them exist in the dictionary. Just in case I miss a more efficient solution.
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.