patternpythonCriticalCanonical
Delete an element from a dictionary
Viewed 0 times
elementdeletefromdictionary
Problem
- How do I delete an item from a dictionary in Python?
- Without modifying the original dictionary, how do I obtain another dictionary with the item removed?
See also How can I remove a key from a Python dictionary? for the specific issue of removing an item (by key) that may not already be present.
Solution
The
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:
The
Note that making a copy for every dict
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 rThe
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).Code Snippets
def removekey(d, key):
r = dict(d)
del r[key]
return rContext
Stack Overflow Q#5844672, score: 2572
Revisions (0)
No revisions yet.