Grade 8 Computer Science · Dictionaries

Why lookup by name is fast

The difference between going over everything and going straight there — and what it is worth.

A thousand orders, a million checks

Searching a list of a thousand names takes the blink of an eye. So why does a program that looks up a customer for each of a thousand orders suddenly turn slow? And there is a structure in which that same lookup takes about the same time whether it holds ten keys or a million.

Until here we saw that a dictionary is more readable. It has a second advantage, and it is far greater than it appears at first sight: it is also faster, in a way that becomes dramatic as the data grows.

The structureLookup time by content
A listGrows in direct proportion to the size
A dictionaryHardly depends on the size
names = ["Ana", "Ben", "Cara"]
found = False
for n in names:
    if n == "Cara":
        found = True

ages = {"Ana": 13, "Ben": 14, "Cara": 13}
print("Cara" in ages)

Why this cost accumulates

One search in a list of a thousand items is imperceptible. But real programs search inside a loop: for each of a thousand orders, find the matching customer. Now there are a million checks instead of a thousand, and the program that seemed immediate becomes slow in a way that is hard to explain. With a dictionary, the same work stays a thousand operations. This is one of the few cases in programming where choosing the right data structure saves more than any attempt to optimise the code itself — and it is worth recognising early.

Example 1 — a search inside a loop

  1. The outer loop runs a thousand times.
  2. Each round searches a list of a thousand.
  3. A million checks in all.
  4. With a dictionary there would have been a thousand.

Example 2 — why the size hardly matters

  1. The dictionary computes from the key where to go.
  2. The computation does not depend on the number of keys.
  3. So it goes straight to one place.
  4. A million keys or ten — nearly the same time.
The cost of a list search is multiplied by every round of the loop; in a dictionary it hardly depends on the size.