dict · Python
del d[key] / pop
Removes a key; pop also returns its value and can take a default.
del d[key]; dict.pop(key[, default])
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
Find the slot, mark it deleted. Iteration order of the remaining keys is unchanged.
Tested example
ages = {"ada": 36, "bob": 25}
del ages["bob"]
assert ages.pop("ada") == 36 # remove and return
assert ages.pop("ada", None) is None # with a default: no KeyError
try:
del ages["ada"]
raise AssertionError("expected KeyError")
except KeyError:
pass
Parameters
- key
- The key to remove.
Behaviour
- Returns
- pop: the removed value (or the default).
- Errors and preconditions
- KeyError if missing (pop without a default).
- Changes
- Removes the entry (CPython marks the slot as a dummy until the next resize).
- Memory and invalidation
- Does not shrink immediately.