Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an item from a dictionary when its key is unknown

What is the best way to remove an item from a dictionary by value, i.e. when the item's key is unknown? Here's a simple approach:

for key, item in some_dict.items():     if item is item_to_remove:         del some_dict[key] 

Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary while iterating it?

like image 893
Buttons840 Avatar asked Mar 27 '11 05:03

Buttons840


People also ask

How do you delete an element in a dictionary with a specific key?

Delete elements of 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. This method takes in the key as the parameter.

How do you remove an item from a key in Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.

What does dictionary get return if key not found?

If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.


1 Answers

The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'

Example:

>>> dic = {'a':1, 'b':2} >>> dic {'a': 1, 'b': 2} >>> dic.pop('c', 0) 0 >>> dic.pop('a', 0) 1 >>> dic {'b': 2} 
like image 79
N 1.1 Avatar answered Oct 03 '22 15:10

N 1.1