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?
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.
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.
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.
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}
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