dict · Python

key in d

Tests whether a key is present. Values are not indexed.

key in d; value in d.values()

Complexity

AverageO(1) for keys
Worst caseO(n) for values (always a scan)
Extra spaceO(1)

Keys go through the hash table; d.values() is just a view to iterate.

Tested example

ages = {"ada": 36}
assert "ada" in ages  # tests keys, by hash then ==
assert 36 not in ages  # values are not searched
assert 36 in ages.values()  # that scan is O(n)
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_dict.py

Parameters

key
The key.

Behaviour

Returns
A bool.
Errors and preconditions
TypeError for an unhashable key.
Changes
Nothing.
Memory and invalidation
No allocation.