Skip to content

How a Python dict keeps insertion order

Deep diveUnder the hood

A hash table stores each key where its hash points, so the order should be scrambled. A Python dict gives your keys back in the order you added them. The trick is two arrays: a dense list of entries and a small, sparse table of indexes into it.

01 The puzzle: a hash table that remembers

Add three keys to a dict and list them. They come back in the order you wrote them, even though a hash table decides where each key lives from its hash.

order.py
d = {}
d["mia"] = 29
d["ana"] = 31
d["bo"] = 25
print(list(d))
Shell
$ python3 order.py
['mia', 'ana', 'bo']

This page is about CPython, the interpreter from python.org. CPython 3.6 switched to the layout below, and Python 3.7 made insertion order part of the language, so every Python 3.7+ interpreter must keep it. Before that, the order you saw was arbitrary.

02 The old picture: one sparse table

Up to Python 3.5, a dict was a single array of slots. Each slot held three 8-byte fields on a 64-bit machine: the key’s hash, a pointer to the key and a pointer to the value. A key went into the slot its hash picked, and a loop walked the slots from 0 up.

To keep the numbers small, this page gives each key a made-up example hash. Real string hashes are 64-bit numbers that change every time Python starts. With 8 slots, the home slot is hash & 7, the lowest three bits.

Example hashes for four keys, in an 8-slot table
KeyExample hashhash & 7Slot used
"mia"1355
"ana"2152 (5 was taken)
"bo"911
"dan"3066
The pre-3.6 layout after the same four inserts (example hashes)
one table · 8 slots of hash, key, value
0empty
1bo: 25
2ana: 31
3empty
4empty
5mia: 29
6dan: 40
7empty
Iteration order: slot by slot
boanamiadan

You inserted mia, ana, bo, dan. A loop over this table returns bo, ana, mia, dan: the order of the hashes, not of your code. Each empty slot still takes its 24 bytes.

Two things are wrong with this. The loop order follows the hashes, so it looks random and can change completely when the table grows. And a table must stay at most two-thirds full to keep probes short, so at least a third of these 24-byte slots are always empty space.

03 The compact layout: entries plus indices

CPython 3.6 split the table in two. The entries array is dense: (hash, key, value) entries, filled strictly from the front. The indices table (dk_indices in CPython’s source) is the sparse hash table, but each slot holds only a small integer: the position of an entry, or -1 for empty.

The hash still picks a slot, but only in the index table. The entry itself always goes on the end of the entries array. Watch the same four keys go in.

Four inserts into the compact layout
Step 1 of 6
Slot —Entries used 0 of 5
indices · 8 slots
-10
-11
-12
-13
-14
-15
-16
-17
entries · room for 5
0
1
2
3
4
  • just written
  • taken, probe on
  • slot picked
  • empty (-1) or free

An 8-slot dict before any insert. Every index slot holds -1, which means empty. The entries array has room for 5 entries, two-thirds of 8.

— key

The order is a side effect of appending. Walking entries from 0 gives mia, ana, bo, dan, the order you inserted them, so a for loop over the dict does exactly that and never looks at the index table. The index table does the hashing; the entries array does the remembering.

A new empty {} in CPython does not allocate either array yet; it shares one read-only empty table. The first insert allocates the 8-slot table shown here.

04 A lookup takes one extra hop

Finding a key is the usual hash table walk, plus one step: read the index slot, then follow it into the entries array to compare.

Looking up d["ana"]
Step 1 of 5
Reads 0
indices · 8 slots
-10
21
12
-13
-14
05
36
-17
entries · room for 5
mia: 290
ana: 311
bo: 252
dan: 403
4
What the lookup has done
Empty
  • index slot read
  • entry checked, not it
  • key matches
  • just done

d["ana"] is called on the dict built above. Nothing is read yet.

"ana" key

The probe sequence is i = (5 × i + 1 + perturb) & mask, where perturb starts as the full hash and is shifted right by 5 bits before each probe. Mixing in the higher bits this way spreads keys that share their lowest bits. A lookup stops at the first -1: if the key existed, it would have been stored there.

05 Why the split also saves memory

The empty slots now live in the index table, where each one is tiny. The 24-byte entries only exist for room the dict can actually use.

Bytes for an 8-slot dict on a 64-bit machine, not counting the dict header
LayoutHash table partEntries partTotal
One table (up to 3.5)8 × 24 = 192—192
Compact (3.6+)8 × 1 = 85 × 24 = 120128

Each index slot is as narrow as the table allows: 1 byte while the table has at most 128 slots, then 2 bytes up to 32,768 slots, then 4, then 8. Since CPython 3.11, a dict whose keys are all strings also leaves the hash out of each entry, because a str caches its own hash. Those entries are 16 bytes.

Before 3.6Order of the hashesA loop walks the sparse table, so the order looks random and can change after a resize.
3.6 and laterOrder of insertionA loop walks the dense entries array, which only ever grows at the end.

06 Deletes leave holes

Deleting a key cannot just set its index slot back to -1. A lookup stops at the first -1, so any key whose probe path ran through that slot would suddenly look missing. Instead, CPython writes a dummy marker, -2, which tells lookups to keep going.

After del d["ana"]
indices · 8 slots
-10
21
2-22
-13
-14
05
36
-17
entries · room for 5
mia: 290
(hole)1
bo: 252
dan: 403
4
  • deleted
  • empty or free

Slot 2 now holds -2, a dummy: “something was here, keep probing”. Entry 1 keeps its place as a hole. Entry 4 is still the only free one, because holes are not reused.

Iteration skips the hole. Holes and dummies stay until the next resize, which builds a fresh index table and copies only the live entries, closing the gaps. It copies them front to back, so the order survives.

The two rules you can see from Python: updating a key keeps its place, because the value is written into its existing entry. Deleting and adding it again puts it at the end, because it gets a new entry.

holes.py
d = {"mia": 29, "ana": 31, "bo": 25}
d["mia"] = 30 # update: keeps its place
print(list(d))
del d["ana"]
d["ana"] = 31 # re-insert: goes to the end
print(list(d))
Shell
$ python3 holes.py
['mia', 'ana', 'bo']
['mia', 'bo', 'ana']

Output from CPython 3.14.

07 When it bites

Insertion order is not a sort order. Re-inserting a key moves it to the end, and == between two dicts ignores order completely. If order is part of what you compare, use OrderedDict or compare list(d.items()).

{"a": 1, "b": 2} == {"b": 2, "a": 1}Equality ignores orderThis is True. Two OrderedDicts with the same items in a different order compare unequal, which is one of the few reasons left to use OrderedDict.
for k in d: del d[k]Changing size while you loopThe loop walks the entries array by position. CPython checks for size changes and raises RuntimeError: dictionary changed size during iteration. Loop over list(d) instead.
for i in range(1000): del d[i]Deleting does not shrinkAn emptied dict keeps its big table: holes and dummies are only cleared by a resize, and deleting never triggers one. Build a new dict, d = dict(d), to get the memory back.
d.popitem()popitem takes the newestSince 3.7 it removes the last entry inserted, like a stack. Older code that treated it as “some arbitrary item” may now always see the same key.

08 Check yourself

Question

A dict was built with keys a, b, c, in that order. You run d["b"] = 9. What does list(d) give?

Question

Why does a delete write -2 into the index slot rather than -1?

Question

In the 8-slot table, how many entries fit before the dict has to grow?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?