d.pop(key)-- consider using this if you need the value for the item being deleted, and/or you want to specify a default value and don't want an exception raised if the key doesn't exist.
e.g.,value = d.pop(key, None)del key-- consider using this if you are certain that the key exists (or you expect an exception if it doesn't), and you don't need the value of the item being deleted.
e.g.,del key
From the official Python language documentation:
del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map.
pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
Answer from Wang Dingwei on Stack Overflowd.pop(key)-- consider using this if you need the value for the item being deleted, and/or you want to specify a default value and don't want an exception raised if the key doesn't exist.
e.g.,value = d.pop(key, None)del key-- consider using this if you are certain that the key exists (or you expect an exception if it doesn't), and you don't need the value of the item being deleted.
e.g.,del key
From the official Python language documentation:
del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map.
pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
pop returns the value of deleted key.
Basically, d.pop(key) evaluates as x = d[key]; del d[key]; return x.
- Use
popwhen you need to know the value of deleted key - Use
delotherwise
Can someone explain me what the difference between pop and remove is that makes sense? Why would you use pop over remove or vice versa?
Thanks!
Videos
I have a dictionary and I wanted to remove one item and documentation mentioned that I can use:
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
del phonebook["John"]
print(phonebook)
or
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
phonebook.pop("John")
print(phonebook)
What's the difference between those two?