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
dictis 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.0andTrueare one key. - The compact layout (CPython 3.6+): a small sparse
indicestable pointing into a denseentriesarray 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.