dict.pop()
Removes a key from a dictionary and returns its value. Give a default to avoid a KeyError when the key is missing.
dict.pop(key[, default])d.pop(key) deletes the entry for key and gives you the value it held, in one step. It is like del d[key], except that you get the value back.
With a second argument, a missing key is fine: d.pop(key, None) simply returns None and changes nothing. This is the usual way to say "remove this key if it is there".
Without a default, a missing key raises KeyError. Note that the default is only used for missing keys; a key that exists with the value None still returns None and is removed.
Parameters
| Parameter | What it is |
|---|---|
keyrequired | The key to remove. |
defaultoptional | Returned when the key is missing. If you leave it out, a missing key raises KeyError. |
Return value
The value that was stored under key, or default if the key was missing.
Examples
1Remove a key and use its value
order = {"id": 1042, "item": "lamp", "note": "leave at door"}
note = order.pop("note")
print(note)
print(order)leave at door
{'id': 1042, 'item': 'lamp'}2Remove if present, with a default
user = {"name": "Ines", "password": "x"}
user.pop("password", None)
user.pop("token", None)
print(user){'name': 'Ines'}The second call finds no "token" key and quietly returns None.
3Rename a key
row = {"nm": "Omar", "age": 28}
row["name"] = row.pop("nm")
print(row){'age': 28, 'name': 'Omar'}The renamed key goes to the end, because it is a newly added key.
4Take out options before passing the rest on
options = {"verbose": True, "size": 10, "color": "blue"}
verbose = options.pop("verbose", False)
print("verbose:", verbose)
print("rest:", options)verbose: True
rest: {'size': 10, 'color': 'blue'}Common mistakes
Popping a missing key without a default
This raises KeyError. Add a default, or check with in first.
cart = {"apple": 2}
try:
cart.pop("pear")
except KeyError:
print("KeyError: no 'pear' in the cart")
print(cart.pop("pear", 0))KeyError: no 'pear' in the cart 0
Calling pop() with no key
Unlike list.pop(), dict.pop() needs the key. To remove the most recently added entry, use dict.popitem().
Questions people ask
What is the difference between dict.pop() and del?
Both remove a key. pop() returns the value and can take a default; del d[key] returns nothing and always raises KeyError for a missing key.
How do I remove a key only if it exists?
d.pop(key, None). It never raises.
How do I remove several keys?
Loop: for k in ["a", "b"]: d.pop(k, None), or build a new dictionary without them with a comprehension.