Delete a dictionary item if the key exists

Simon Hughes picture Simon Hughes · Mar 14, 2013 · Viewed 164.9k times · Source

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.

Answer

Adem Öztaş picture Adem Öztaş · Mar 14, 2013

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.