dict · Python

d[key] = value / setdefault

Adds a key or replaces its value; setdefault adds only when missing.

d[key] = value; dict.setdefault(key, default=None, /)

Complexity

AverageO(1)
AmortizedO(1) including resizes
Worst caseO(n)
Extra spaceO(1) amortized

Assumes: Hashes spread well; the worst case needs many collisions.

Hash the key, probe the index table for a free or matching slot, append to the entries array. Resizing rebuilds the table occasionally.

Tested example

ages: dict[str, int] = {}
ages["ada"] = 36  # adds
ages["ada"] = 37  # replaces: keys are unique
ages["bob"] = 25
assert ages == {"ada": 37, "bob": 25}
assert list(ages) == ["ada", "bob"]  # insertion order is guaranteed (3.7+)
ages.setdefault("cy", 41)  # adds only if missing
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_dict.py

Parameters

key
Any hashable object.

Behaviour

Returns
Assignment: nothing. setdefault: the value now stored.
Errors and preconditions
TypeError for an unhashable key.
Changes
Adds or replaces one entry; may resize.
Memory and invalidation
May resize. Invalidates running iterators (RuntimeError if the size changes).