dict.pop()
Remove a key and get its value back — with a default to make missing keys safe.
Common call
options.pop("debug", False)
Returns
removed value or default; dict shrinks on hit
Replaces
del d[key] removes without returning
Watch out
no default + missing key = KeyError
dict.pop(key[, default])
→ Any
Demo
Live evaluation
Try:
Inputs
dictdictkey: value pairs
keystrkey to remove
defaultAnyempty = no default
Output
{'a': '1', 'b': '2'}.pop('a')
'1'
The demo shows the RETURN value. In real code a hit also removes the key — after {"a": 1}.pop("a") the dict is empty. Leave the default field empty to see the bare-pop KeyError.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | hashable | yes | The key to remove. |
| default | Any | no ((no default)) | Returned when the key is absent. Without it, a missing key raises KeyError. |
Return value
Any — The removed value; or default when the key is absent and a default was given. Absent key without default raises KeyError.
Common patterns
Consume optional kwargs
Take an option out of a dict, leaving only what remains.
debug = options.pop("debug", False) # options no longer contains "debug"
Rename a key
pop + assignment in one line.
d["new_name"] = d.pop("old_name")
Remove-if-present
The default makes removal unconditional and quiet.
cache.pop(session_id, None)
Examples
1. Pop an existing key
{"a": 1, "b": 2}.pop("a")
Returns
12. Missing key with default
{"a": 1}.pop("z", 0)
Returns
03. Default None as quiet remove
{"a": 1}.pop("z", None)
Returns
NonePitfalls
1. Bare pop on a missing key raises
Pass a default whenever absence is a legal state.
Raises
{"a": 1}.pop("z")
KeyError: 'z'
Fix
{"a": 1}.pop("z", None)
None
2. pop both mutates and returns
Using it just to read a value silently deletes the key.
Key lost
value = d.pop("k") # "k" is gone from d
dict is smaller now
Read without removing
value = d.get("k")
dict unchanged
3. dict.pop vs list.pop
Same name, different contracts: dicts pop by KEY with optional default; lists pop by INDEX with none.
Wrong mental model
d.pop() # lists allow this
TypeError: pop expected at least 1 argument, got 0
Dicts need the key
d.pop("k", None)
value or None
When to use
Use it
- Take-and-remove in one step (options, queues keyed by id)
- Quiet removal with a default
- Renaming keys
Reach for something else
- Read without removing → dict.get
- Remove without needing the value → del d[key]
- Remove an arbitrary item → dict.popitem
Notes
Complexity
O(1) average — hash lookup + delete
Return
removed value or default; dict mutates on hit
CPython impl
Objects/dictobject.c :: dict_pop_impl
Memory
May shrink the table on many deletions
Thread-safe
No — mutating shared dicts needs a lock
FAQ
pop returns the value and accepts a default for missing keys; del returns nothing and always raises on a missing key.
v = d.pop("k", None) # value or None del d["k"] # raises if absent
History
2.0
Core dict method, unchanged semantics since.