man python/dict
How a Python dict works
One of the most common Python idioms counts how often each value appears:
counts = {}
for n in ids:
counts[n] = counts.get(n, 0) + 1
and later asks n in counts. Neither line slows down in proportion to the size of counts. This article reads CPython’s Objects/dictobject.c at tag v3.15.2 to see why. Every number below comes from that source, from the official “What’s New” pages, or from a command I ran. Timings are from Python 3.15.2 on an Apple M2 Pro. In the terminal output, comments after # are my annotations.
Two arrays instead of one
A dict points to a keys object. The header comment in dictobject.c draws it as a small header followed by two arrays, dk_indices and dk_entries.
dk_indices: the hash table, 8 slots
slot: 0 1 2 3 4 5 6 7
+----+----+----+----+----+----+----+----+
| -1 | 1 | -1 | 0 | -1 | -1 | 2 | -1 |
+----+----+----+----+----+----+----+----+
-1 = DKIX_EMPTY, -2 = DKIX_DUMMY
dk_entries: insertion order, 5 usable
+---+-------------------+
| 0 | hash, key, value |
| 1 | hash, key, value |
| 2 | hash, key, value |
| 3 | (free) |
| 4 | (free) |
+---+-------------------+
dk_indices is the real hash table. Each slot holds either an index into dk_entries, or -1 for “never used”, or -2 for “deleted”. The slot width grows with the table. It is one byte per slot up to 128 slots, two bytes up to 2**15, four bytes up to 2**31, and eight beyond that. dk_entries is a dense array of entries in insertion order, and it has room for two thirds of the slot count.
Python 3.5 stored one array of full entries, one per slot. Its new_keys_object allocates sizeof(PyDictKeyEntry) * size bytes, so at least a third of those 24-byte entries were always empty. For an 8-slot table the 3.5 layout spends 8 × 24 = 192 bytes on the table. The current one spends 8 one-byte indices plus 5 × 24 bytes of entries, 128 bytes in total. The 3.6 What’s New page reports the new dict as “between 20% and 25% smaller compared to Python 3.5”.
Ordering falls out of the layout. New entries are appended to dk_entries, so iterating the array visits keys in the order they were inserted. In 3.6 that was “considered an implementation detail and should not be relied upon”. The 3.7 What’s New page says insertion-order preservation “has been declared to be an official part of the Python language spec”.
Finding the slot
A lookup in do_lookup() is short:
size_t mask = DK_MASK(dk);
size_t perturb = hash;
size_t i = (size_t)hash & mask;
for (;;) {
ix = dictkeys_get_index(dk, i);
if (ix >= 0) { /* compare the entry's key; return ix on a match */ }
else if (ix == DKIX_EMPTY) { return DKIX_EMPTY; }
perturb >>= PERTURB_SHIFT;
i = mask & (i*5 + perturb + 1);
}
The table size is a power of two, so hash & mask keeps the low bits of the hash as the first slot. If that slot points at an entry, CPython compares keys. compare_generic() first checks identity (ep->me_key == key), then compares the stored hash, and only then calls ==. If the slot is empty, the key is absent. A collision moves on to the next slot in the probe sequence. This is open addressing. The source cites Knuth’s Algorithm D and says open addressing was chosen because chaining would add link overhead of “100% with typical malloc overhead”.
n in counts is dict_contains(), which hashes the key and runs this same lookup. counts.get(n, 0) is dict_get_impl(), which does the same and returns the default on DKIX_EMPTY.
Ints hash to themselves
For an int that fits in one internal digit, long_hash() in longobject.c returns the value itself. Larger ints are reduced modulo the prime 2**61 - 1 on 64-bit builds. The one exception is -1. CPython uses a hash of -1 to signal an error, and dict_contains() and dict_get_impl() both treat hash == -1 as a failure, so long_hash() turns -1 into -2.
$ python3.15 hashes.py
[0, 1, 2, 3] # [hash(i) for i in range(4)]
-2 -2 # hash(-1), hash(-2)
0 1 6 # hash(2**61 - 1), hash(2**61), hash(2**61 + 5)
a b 2 # d = {-1: "a", -2: "b"}; d[-1], d[-2], len(d)
The dict still keeps -1 and -2 apart, because equal hashes only lead to an == check.
The source defends identity hashing directly. With ints as their own hash, “there are no collisions at all for dicts indexed by a contiguous range of ints”. For IDs that are small consecutive numbers, the first probe usually lands on the right entry.
The perturb trick
Identity hashing has a weak spot, and the comment gives the example. The keys [i << 16 for i in range(20000)] fit in a table of 2**15 slots, and the low 15 bits of every one are zero. They all start at the same slot.
The fix is the probe recurrence. Plain j = (5*j + 1) mod 2**i visits every slot exactly once. For 8 slots the source lists the order as 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3. CPython also adds perturb, which starts as the full hash and loses PERTURB_SHIFT = 5 bits per step, so the high bits of the hash steer later probes. Once perturb reaches zero, the plain recurrence still guarantees an empty slot. I copied the loop into Python to see four hashes that share their low bits:
$ python3.15 probe.py # probe(h, size=8, steps=8)
0 [0, 1, 6, 7, 4, 5, 2, 3]
65536 [0, 1, 6, 1, 6, 7, 4, 5]
131072 [0, 1, 6, 3, 0, 1, 6, 7]
196608 [0, 1, 6, 5, 2, 3, 0, 1]
They share three probes and then split apart. shifted.py times dict.fromkeys() on the 20,000 shifted keys against range(20000). It first confirms that every shifted key has the same low 15 bits.
$ python3.15 shifted.py
1
range 282.2 us
i << 16 687.3 us
Every key starts at the same slot, and the build is about 2.4 times slower.
The source says 5 was “the best” shift in Tim Peters’ experiments, and 4 and 6 “weren’t significantly worse”.
When the table fills up
The load factor is a macro:
#define USABLE_FRACTION(n) (((n) << 1)/3)
#define GROWTH_RATE(d) ((d)->ma_used*3)
A table of n slots holds at most 2n/3 entries. Every insert of a new key decrements dk_usable. When it reaches zero, insertion_resize() picks the smallest power of two that is at least GROWTH_RATE, three times the number of live items. An empty {} allocates no table at all. It shares an immortal empty keys object, and the first insert creates the 8-slot minimum (PyDict_MINSIZE). You can watch the steps with sys.getsizeof:
import sys
d = {}
last = sys.getsizeof(d)
print(0, last)
for i in range(1, 200):
d[i] = 1
s = sys.getsizeof(d)
if s != last:
print(i, s)
last = s
$ python3.15 growth.py
0 64
1 224
6 352
11 632
22 1168
43 2264
86 4688
171 9304
The first line is the empty dict, and the second is the first insert, which allocates the 8-slot table. Every later line is the insert that triggered a resize. At the 6th insert there are 5 live keys, 5 × 3 = 15, so the table goes from 8 to 16 slots (10 usable). Then 10 × 3 = 30 gives 32 slots, 21 × 3 = 63 gives 64, and so on. The table doubles at every step. Every row after the first also fits 96 + index bytes + 24 × usable entries. For 256 slots that is 96 + 512 + 170 × 24 = 4688, with two bytes per index slot.
A resize allocates a new keys object, copies the live entries in order, and rebuilds the index with build_indices_generic(). That function reuses the hash stored in each entry. It never calls __hash__ or __eq__. A key class that counts its calls confirms it:
$ python3.15 hashcalls.py
build: {'hash': 1000, 'eq': 0} # 1000 inserts through 8 resizes
count: {'hash': 2000, 'eq': 0} # d[k] = d.get(k, 0) + 1 for each key
The counting idiom costs two hashes per item, one for get and one for the store. __eq__ never ran because each lookup used the same key object, and the identity check matched first.
Deleting leaves dummies
del d[k] writes DKIX_DUMMY into the index slot and clears the entry. The slot cannot go back to empty. The source explains that “the probe sequence in case of collision would have no way to know they were once active”. The default build lets a later insert reuse a dummy index slot. The free-threaded build never reuses them. The entry array itself only grows until the next resize. Since GROWTH_RATE counts live items, a resize after many deletions can produce a smaller table.
$ python3.15 deletes.py
100 keys: 4688
after deleting all: 0 4688
one insert later: 4688
churn sizes seen: [224, 352]
Deleting every key frees nothing. The churn loop inserts 100,000 keys and deletes all but five, and the dict never grew past 352 bytes, because each resize compacted it back to 16 slots.
What it costs
The source keeps the load below 2/3 so that “we usually find the key we’re looking for on the first try”. dictnotes.txt says single-key operations “can be O(1) unless resizing is possible”. That gives:
d[k],k in d,d.get(k), andd[k] = vfor an existing key are O(1) on average.- Inserting a new key is O(1) amortised. In the growth run, by the time the dict reached 171 keys its resizes had moved 5 + 10 + 21 + 42 + 85 + 170 = 333 entries, under two moves per key.
- The worst case is O(n) per operation, when every key lands on the same probe path.
Membership timing barely moves with size:
$ python3.15 -m timeit -s "counts = {i: 1 for i in range(10)}; k = 5" "k in counts"
20000000 loops, best of 5: 11.4 nsec per loop
$ python3.15 -m timeit -s "counts = {i: 1 for i in range(1000)}; k = 500" "k in counts"
20000000 loops, best of 5: 10.8 nsec per loop
$ python3.15 -m timeit -s "counts = {i: 1 for i in range(1000000)}; k = 500000" "k in counts"
20000000 loops, best of 5: 18.7 nsec per loop
These figures include the timeit loop overhead. Forcing the worst case is easy. A class whose __hash__ returns 42 for every instance builds a dict roughly four times slower each time n doubles:
$ python3.15 collide.py
Good n= 1000 0.07 ms
Good n= 2000 0.15 ms
Good n= 4000 0.25 ms
Bad n= 1000 23.70 ms
Bad n= 2000 108.38 ms
Bad n= 4000 355.65 ms
Counting n items into k distinct keys does n lookups and n stores, each O(1) expected. The dict only ever holds k keys, so its resizes move fewer than 2k entries in total. That sums to O(n + k), and k is at most n, so the whole count is O(n) expected. Measured with k = 1000:
$ python3.15 count_scaling.py
n= 100,000 2.9 ms 29.0 ns/item
n= 1,000,000 29.7 ms 29.7 ns/item
n=10,000,000 334.7 ms 33.5 ns/item
Specialised tables
The keys object has three kinds: DICT_KEYS_GENERAL, DICT_KEYS_UNICODE and DICT_KEYS_SPLIT.
Unicode-only tables. When every key is an exact str, entries use PyDictUnicodeEntry, which holds only key and value. The hash is read from the string object, which caches it. That saves 8 bytes per usable entry. compare_unicode_unicode() checks identity, then the hash, then unicode_eq(), so it never calls a Python-level __eq__. Insert one non-str key and the dict is rebuilt as a general table:
$ python3.15 kinds.py
184 224 # {c: 0 for c in "abcde"}, {i: 0 for i in range(5)}
352 # after s[1] = 0 on the str-keyed dict
The 40-byte gap is 5 usable entries × 8 bytes of hash.
Split (key-sharing) tables. Instances of one class usually have the same attribute names. A class defined in Python can have one shared keys object, with each instance’s values in a separate array. In 3.15.2 the shared table has 64 slots, and its capacity comes from SHARED_KEYS_MAX_SIZE, which is 30. A class whose __init__ assigns 29, 30 or 31 attributes shows the cap:
$ python3.15 sharelimit2.py # attributes, len(__static_attributes__), getsizeof(obj.__dict__)
29 29 304
30 30 304
31 31 832
Up to 30, the dict is 64 bytes plus 30 value pointers. At 31 it reports 832, the size of an ordinary 64-slot str-keyed table. _PyDict_NewKeysForClass() pre-fills it from the class’s __static_attributes__, the tuple of names the compiler saw assigned as self.<name>. Split tables accept only str keys. A non-str key, a full shared table or any resize turns the dict into an ordinary combined table. dictnotes.txt estimates the saving at “about 60% memory” for instance dicts.
Curious facts
hash(-1) == hash(-2)isTrue. -1 is the C-level error signal, solong_hash()maps it to -2.hash(2**61) == 1on 64-bit builds, because integer hashes reduce modulo the prime2**61 - 1.dictnotes.txtlistsd[e] = d.get(e,0) + 1as a principal use case, and sayssetdefaultexists partly to combine two lookups into one.- Every new instance of a class shrinks the class’s spare shared-key capacity by one, down to a minimum of one (
_PyObject_InitInlineValues()). With two instances of a two-attributePointclass,sys.getsizeof(p.__dict__)reports 288 bytes (split.py). After 1,000 instances, the first and the last both report 88 (share2.py). - The header comment of
dictobject.cstill says split keys “have a maximum size of 16”. The constant inpycore_dict.his 30. - A resize never calls
__hash__or__eq__on your keys.
Version history
- 3.3: key-sharing dictionaries (PEP 412) for object attributes. The growth rate was
used*2, down fromused*4up to 3.2, per the comment aboveGROWTH_RATE. - 3.4 to 3.6: growth rate
used*2 + size/2. I confirmed this formula indictobject.cat v3.6.0 and v3.6.15. - 3.6: compact layout, 20% to 25% smaller than 3.5. Insertion order kept as an implementation detail.
- 3.7: insertion order becomes part of the language spec.
GROWTH_RATEisused*3at v3.7.0, as it still is at v3.15.2. - 3.11: dicts whose keys are all
strstop storing hashes. What’s New citessys.getsizeof(dict.fromkeys("abcdefg"))dropping from 352 to 272 bytes. My runs give 272 on 3.12.16 and 3.15.2, and 360 on 3.9.6. 3.11 also made siphash13 the default hash forstrandbytes.sys.hash_info.algorithmreportssiphash24on 3.9.6 andsiphash13on 3.12 to 3.15. - 3.13: classes gain
__static_attributes__, which the 3.15.2 source uses to seed shared keys. - 3.15:
frozendictjoins the builtins (PEP 814). It is implemented in the samedictobject.c.
Sources
CPython v3.15.2:
- dictobject.c#L9-L50 layout and index widths
- dictobject.c#L66-L106 slot states, dummies, insertion order, the stale “16”
- dictobject.c#L108-L116
PyDict_MINSIZE - dictobject.c#L139
frozendict_new - dictobject.c#L329-L421
PERTURB_SHIFTand the probe sequence notes - dictobject.c#L570-L628
USABLE_FRACTION,calculate_log2_keysize,GROWTH_RATE - dictobject.c#L636-L651 shared empty keys
- dictobject.c#L793-L847
new_keys_object - dictobject.c#L1081-L1123
do_lookup - dictobject.c#L1160-L1207 key comparison
- dictobject.c#L1312-L1391
_Py_dict_lookup - dictobject.c#L1832-L1909
find_empty_slot,insertion_resize,insert_combined_dict - dictobject.c#L2000-L2049
insertdict - dictobject.c#L2097-L2129
build_indices_* - dictobject.c#L2141-L2299
dictresize - dictobject.c#L2882-L2923
delitem_common - dictobject.c#L4750-L4769
dict_get_impl - dictobject.c#L5235-L5244
dict_contains - dictobject.c#L7232-L7295
_PyDict_NewKeysForClass,_PyObject_InitInlineValues - dictnotes.txt#L26-L59 use cases, including counting
- dictnotes.txt#L93-L118 O(1) note, key-sharing saving
- pycore_dict.h#L85-L95 entry structs
- pycore_dict.h#L189-L197
DKIX_*and key kinds - pycore_dict.h#L248
SHARED_KEYS_MAX_SIZE - longobject.c#L3673-L3743
long_hash - cpython/pyhash.h#L12-L18
PyHASH_BITS,PyHASH_MODULUS - pyhash.h#L42-L48 default hash algorithm
Older tags: v3.5.0 dictobject.c#L318-L345 (one entry per slot), v3.6.15 GROWTH_RATE, v3.7.0 GROWTH_RATE.
grep -rl /lib/python/dict/
ls python/
- draft Counter, most_common and heapq: top-k in the standard libraryHow collections.Counter counts, how most_common and heapq.nsmallest pick the top few, and why they break ties in opposite directions, read from the CPython 3.15.2 source.
- draft How Python sorts: runs, galloping and powersortWhat CPython 3.15's list.sort does with your data: natural runs, binary insertion sort, a powersort merge stack, galloping, and type-specialised compares.
- draft Multiplying a list in Python: loops, reduce, operator.mul and math.prodWhat a for loop, functools.reduce with a lambda or operator.mul, and math.prod actually execute in CPython 3.15, how fast each one is, and what changes once the product outgrows a machine word.