Is there a way to delete an item from a dictionary in Python?
Additionally, how can I delete an item from a dictionary to return a copy (i.e., not modifying the original)?
Another method is “popitem()”. It removes and returns a random element (key, value) from the dictionary. If you like to drop all the elements from the dictionary, then use the “clear()” method to flush everything. Nonetheless, one more way to remove an element from a dictionary is to use the del keyword.
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.
The del
statement removes an element:
del d[key]
Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:
def removekey(d, key): r = dict(d) del r[key] return r
The dict()
constructor makes a shallow copy. To make a deep copy, see the copy
module.
Note that making a copy for every dict del
/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).
pop
mutates the dictionary.
>>> lol = {"hello": "gdbye"} >>> lol.pop("hello") 'gdbye' >>> lol {}
If you want to keep the original you could just copy it.
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