Best method to delete an item from a dict [closed]
In Python there are at least two methods to delete an item from a dict using a key.
d = {"keyA": 123, "keyB": 456, "keyC": 789}
#remove via pop
d.pop("keyA")
#remove via del
del d["keyB"]
Both methods would remove the item from the dict.
I wonder what the difference between these methods is and in what kinds of situations I should use one or the other.
Use
d.pop
if you want to capture the removed item, like initem = d.pop("keyA")
.Use
del
if you want to delete an item from a dictionary.If you want to delete, suppressing an error if the key isn't in the dictionary:
if thekey in thedict: del thedict[thekey]
pop
returns the value of deleted key.
Basically, d.pop(key)
evaluates as x = d[key]; del d[key]; return x
.
- Use
pop
when you need to know the value of deleted key - Use
del
otherwise
Most of the time the most useful one actually is:
d.pop("keyC", None)
which removes the key from the dict, but does not raise a KeyError
if it didn't exist.
The expression also conveniently returns the value under the key, or None
if there wasn't one.
I guess it comes down to if you need the removed item returned or not. pop
returns the item removed, del
does not.