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 remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set.
To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method.
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.
There is also:
try: del mydict[key] except KeyError: pass
This only does 1 lookup instead of 2. However, except
clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With