python - Delete an item from a dictionary -
is there way delete item dictionary in python?
i know can call .pop
on dictionary, returns item removed. i'm looking returns dictionary minus element in question.
at present have helper function accepts dictionary in question parameter, , returns dictionary item removed, there more elegant solution?
the del
statement removes element:
del d[key]
however, mutates existing dictionary contents of dictionary changes else has reference same instance. return new dictionary, make copy of dictionary:
def removekey(d, key): r = dict(d) del r[key] return r
the dict()
constructor makes shallow copy. make deep copy, see copy
module.
Comments
Post a Comment