Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a dictionary item if the key exists [duplicate]

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.

like image 624
Simon Hughes Avatar asked Mar 14 '13 13:03

Simon Hughes


People also ask

How do you remove duplicate keys in Python?

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.

Which would you use to delete an existing key value pair from a dictionary?

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.


2 Answers

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.

like image 59
Adem Öztaş Avatar answered Oct 19 '22 04:10

Adem Öztaş


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.

like image 43
mgilson Avatar answered Oct 19 '22 04:10

mgilson