Skip to the solution
EasyDSA13 min read

How are Python dictionaries implemented and ordered?

724 views

The problem

Question presented to candidate: "Dictionaries are everywhere in Python. How does a dict actually find a value by its key so fast, and why does it remember the order you inserted things in? Was that always the case?"

What a strong answer should cover:

  • A dict is a hash table: hash(key) picks a starting slot, collisions are resolved by open addressing (probing other slots), and == confirms the match, giving average O(1) get, set and delete.
  • Keys must be hashable; equal keys must hash alike, which is why 1, 1.0 and True are one key.
  • The compact layout (CPython 3.6+): a small sparse indices table pointing into a dense entries array of (hash, key, value) kept in insertion order. Iteration walks the dense array, which is where the order comes from.
  • The version fact: insertion order was a CPython 3.6 implementation detail and became a language guarantee in 3.7; updating a value keeps the position, delete + re-insert moves the key to the end.
  • Resizing keeps the table at most about two thirds full; worst case lookup is O(n) when many keys collide.

Code / implementation expected: Optional โ€” a short demo of ordering rules, or a sketch of the indices + entries layout.

  • dict
  • data-structures

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonDict ordering rules, key equality and resize points
PythonA model of the compact dict: indices, entries and probing

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 14 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How do you read TOML with tomllib in Python 3.11+?

Continue