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.
The clear() method removes all items from the dictionary.
To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.
Use d.pop
if you want to capture the removed item, like in item = 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
.
pop
when you need to know the value of deleted keydel
otherwiseIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With