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

AverageO(1)
Worst caseO(n)
Extra spaceO(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
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_dict.py

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.