Skip to content
BIASED

Dictionaries and sets

Block 1 of 8~2 min

Finding by key

The topic Lists and tuples ended on a limit of the list. It finds an item by position in O(1)O(1), but finding an item by its value, x in xs, compares against the items one by one: O(n)O(n).

Here is where that hurts. Count the words of a small corpus with a list of [word, count] pairs:

corpus = "the cat sat on the mat the end".split()
pairs = []                      # [word, count] pairs
for w in corpus:
    for p in pairs:
        if p[0] == w:           # compare with each stored word
            p[1] += 1
            break
    else:                       # no pair matched: a new word
        pairs.append([w, 1])
print(pairs)
[['the', 3], ['cat', 1], ['sat', 1], ['on', 1], ['mat', 1], ['end', 1]]

It works, but every word of the corpus walks the list of words seen so far. With a vocabulary of VV distinct words, each step costs up to VV comparisons.

A dictionary, dict, maps keys to values and finds a key without walking anything. The same counter:

corpus = "the cat sat on the mat the end".split()
counts = {}
for w in corpus:
    if w in counts:
        counts[w] += 1
    else:
        counts[w] = 1
print(counts)
print(counts["the"], "mat" in counts, len(counts))
{'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1}
3 True 6

counts[w] reads or writes the value of key w, and w in counts asks whether the key is there. A set is the same structure with keys and no values. How fast is it? On one Apple M1 with CPython 3.14.7, x in xs for the last of 10510^5 integers in a list took about 840,000 ns. The same test on a set took about 35 ns, and still about 35 ns with 10610^6 items, where the list took about 8 ms. Your timings will differ; the gap will not.

Both dict and set are hash tables. This topic shows how a hash table finds a key, how CPython lays it out in memory, when it grows, which objects can be keys, and when the speed is lost.

Answers are saved on the server and tied to this browser until you sign in.