dict. pop()
Removes a key from a dictionary and returns its value, optionally with a fallback value.
- Returns
- The value of the removed key, or
default. - Changes the original
- Yes
Example
#user = {"name": "Jack", "email": "jack@example.com", "token": "a1b2c3"}
token = user.pop("token")
print(token)
print(user)
print(user.pop("token", "none"))Definition and usage
#The pop(key) method removes an entry from the dictionary and returns the value that was stored under that key. It comes in handy when you want to take data out and get rid of it at the same time, for example moving a field to another structure or stripping it before sending data onward.
When the key is missing, pop() raises KeyError. If you pass a second argument, it is returned instead of the error, and the dictionary stays unchanged. Writing data.pop("tmp", None) is a safe way to remove a key that might not exist.
Related tools are the del dict[key] statement, which removes an entry without returning the value, and the popitem() method, which removes and returns the most recently added pair.
Syntax
#dict.pop(key)
dict.pop(key, default)Parameters
#key
a dictionary key
The key to remove.default
optional
The value returned when the key is missing. Without it, a missing key raisesKeyError.
More examples
#cart = {"HTML": 49}
try:
cart.pop("Python")
except KeyError as error:
print("KeyError:", error)queue = {"task_1": "HTML", "task_2": "CSS", "task_3": "Python"}
print(queue.popitem())
del queue["task_1"]
print(queue)Good practices
#- Remove a key that might not exist with
pop(key, None). Then you need neither a condition nor atryblock. - When you don't need the value of the removed key,
del dict[key]is the shorter way to write it.
Related entries
#- dict.get()Returns the value for a key, or a default value when the key is not in the dictionary.
- dict.update()Adds pairs from another dictionary or from arguments to a dictionary, overwriting existing keys.
- list.pop()Removes the item at the given index (the last one by default) and returns it.
- set.discard()Removes an element from a set if it's there. A missing element causes no error.
- try, except, else, finallyException handling: catching errors without stopping the program.
Spotted a mistake or missing an example? Write to us.