Best method to delete an item from a dict
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.
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
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]