Advertisement
Advanced Python, Data Types & Structures

How do dictionaries maintain insertion order internally since Python 3.7, and what data structure change made this both possible and efficient?

Short answer

CPython's dict implementation (since 3.6 as an implementation detail, guaranteed by the language spec since 3.7) uses a COMPACT internal representation: a separate, order-preserving array of entries alongside a sparse hash table of INDICES into that array — this achieves both…

Save Python mock interview
Advertisement
AModel answer
CPython's dict implementation (since 3.6 as an implementation detail, guaranteed by the language spec since 3.7) uses a COMPACT internal representation: a separate, order-preserving array of entries alongside a sparse hash table of INDICES into that array — this achieves both O(1) average hash-based lookup AND stable insertion-order iteration, unlike the older implementation which stored entries directly in hash-table slot order.
d = {}
d["z"] = 1
d["a"] = 2
d["m"] = 3
print(list(d.keys()))  # ['z', 'a', 'm'] -- insertion order preserved, NOT alphabetical or hash order
Real-world example
Relying on dict insertion order being preserved for building an ordered configuration or an ordered API response body.
Likely follow-ups
  • Before Python 3.7, what dedicated class from the collections module was needed to guarantee this same ordering behavior?
Related topics