Python · Hash map · container

dict

Python's built-in hash table from hashable keys to values, with average O(1) operations and guaranteed insertion order.

# built in: no import
class dict(**kwargs) / dict(mapping, /, **kwargs) / dict(iterable, /, **kwargs)

CPython 3.14 (insertion order guaranteed since 3.7)

Operations

OperationTimeWorst caseChanges the collection
d[key] = value / setdefaultO(1) including resizesO(n)Yes
d[key]O(1)O(n)No
getO(1)O(n)Yes
key in dO(1) for keysO(n) for values (always a scan)No
del d[key] / popO(1)O(n)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
In CPython, a compact layout: a dense entries array in insertion order plus a sparse index table using open addressing with a perturbed probe sequence.
Ordering
Insertion order is guaranteed (language guarantee since Python 3.7). Re-assigning an existing key keeps its position.
Duplicates
Keys are unique; values may repeat.
Mutability
Mutable. Adding or removing keys during iteration raises RuntimeError.
Memory and ownership
Keys must be hashable (immutable built-ins, or objects with consistent __hash__ and __eq__).
Equality and comparison
Keys are matched by hash, then identity or ==. 1, 1.0 and True are the same key because they are equal and hash equally.

Unlike C# SortedDictionary, Java TreeMap and C++ std::map, Python ships no balanced-tree ordered map.

Pitfalls

  • d[k] raises KeyError for a missing key; use get, setdefault or collections.defaultdict.
  • Lists cannot be keys (unhashable); use tuples.
  • Mutating a key object's hash-relevant state after insertion breaks lookups.

Alternatives

  • collections.defaultdict for automatic defaults
  • collections.Counter for counting
  • There is no sorted map in the standard library: keep a sorted list of keys with bisect, or use a third-party package

In other languages

References