Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresMiddleCommonTheory

Do Python dictionaries preserve insertion order, and how does key lookup achieve near O(1) time?

Answer

Since Python 3.7, insertion order preservation is a guaranteed language feature, not an implementation detail — iterating a dict yields keys in the order they were first inserted. Lookup is fast because a dict is a hash table: each key's hash determines a bucket, and equal keys must also have equal hashes, so `__eq__` and `__hash__` must stay consistent on any custom key type. Average-case get/set/delete is O(1), though a pathological hash collision pattern can degrade that.

Strong answer includes

  • insertion order guaranteed since 3.7
  • hash table with buckets keyed by hash
  • custom keys need consistent __eq__ and __hash__

Practical example

A custom `UserId` class used as a dict key must define both `__eq__` and `__hash__` consistently; otherwise two logically equal `UserId` instances could hash to different buckets and never be recognized as the same key.

#dict#hashing

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modulesData modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols