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).
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.
Delete item from dict Python
Python - How to delete an item/value from a key in a dictionary?
Can we have a .discard() for dictionary please - Ideas - Discussions on Python.org
Can we have a .delete() for dictionary please
Videos
Hello,
I have this dictionary:
defaultdict={'UP 1': 1, 'P sMaple-sMary': 36, 'UP sMaple': 14, 'UP sMary': 32, 'P sJewell-sCynthia': 3, 'UP sJewell': 0, 'UP sCynthia': 4, 'P sPamela-sRachel': 1, 'UP sPamela': 0, 'UP sRachel': 0, 'P sSylvia-sElsie': 1, 'UP sSylvia': 0, 'UP sElsie': 5, 'P sMarcelene-sMaria': 7, 'UP sMarcelene': 5}
And I want to remove item if it starts UP. I tried the following code but it does not work
key_to_remove="UP" del defaultdict[key_to_remove] #I tried to remove res2 = Counter(defaultdict.values()) 3after removing, I wanted to count each value print(res2)
I know that I can delete a key using del but I don't know if I can remove an item and leave the key as it is.