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 structure | Lookup time by content |
|---|---|
| A list | Grows in direct proportion to the size |
| A dictionary | Hardly 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
- The outer loop runs a thousand times.
- Each round searches a list of a thousand.
- A million checks in all.
- With a dictionary there would have been a thousand.
Example 2 — why the size hardly matters
- The dictionary computes from the key where to go.
- The computation does not depend on the number of keys.
- So it goes straight to one place.
- A million keys or ten — nearly the same time.