Grade 8 Computer Science · Dictionaries

What can serve as a key

Two conditions, and why they follow straight from how a dictionary works.

The dictionary that came out too small

A program goes over a hundred students and puts each of them in a dictionary. At the end it holds only ninety-seven, and no message ever appeared. No student was deleted, so where did three of them go?

Not every value can serve as a key, and there are two good reasons for that. Both follow straight from the mechanism seen in the previous lesson — and once it is understood, the restrictions stop looking arbitrary.

The conditionWhere it follows from
UniquenessOne key leads to one place
FixednessThe computation is made from the key itself
scores = {"Ana": 90}
scores["Ana"] = 95
print(scores)
print(len(scores))

The silent replacement

The first condition produces the commonest bug with dictionaries, and it is worth knowing: if you build a dictionary in a loop and two different items produce the same key, the second will overwrite the first and the dictionary will come out smaller than you expected. There is no message at all — the program did exactly what it was asked. The sign that identifies this is immediate: compare the dictionary’s length with the number of items you went over. If it is smaller, you have repeating keys, and that nearly always means the key you chose is not truly a unique identifier.

Example 1 — why a list is not a key

  1. The dictionary computed from the key where to go.
  2. A list can change after the insertion.
  3. Then the computation would lead elsewhere.
  4. And the inserted value would be lost.

Example 2 — spotting repeating keys

  1. Count how many items were gone over.
  2. Compare with the length of the dictionary built.
  3. If it is smaller — there were overwrites.
  4. A sign the key is not a unique identifier.
The silent replacement: the program did exactly what it was asked.