dict · Python

d[key]

Returns the value for a key; raises KeyError if it is missing.

d[key]

Complexity

AverageO(1)
Worst caseO(n)
Extra spaceO(1)

Assumes: Good hash distribution.

One hash and a short probe sequence.

Tested example

ages = {"ada": 36}
assert ages["ada"] == 36
try:
    ages["nobody"]
    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.

Behaviour

Returns
The value.
Errors and preconditions
KeyError if missing (a dict subclass can define __missing__ instead, as defaultdict does).
Changes
Nothing.
Memory and invalidation
No allocation.