Grade 8 Computer Science · Dictionaries

Common mistakes about dictionaries

Six mistakes, most of them around keys that are not what you thought.

“Ana” and “Ana ” are not the same student

When a dictionary gives an error on a key you are sure you put in, the natural thing is to suspect the data. Almost always the problem is somewhere else entirely, and it is hard to see with the eye. What can you print to find it within a second?

The dictionary itself is almost never the problem. The problems live in the keys: a key that is not unique, a key that does not exist, and a key that is not exactly what you wrote.

Example 1 — a key that looks identical and is not

  1. At insertion the key was written with no space.
  2. At access the same key was written with a space.
  3. To the eye they are identical; to the computer not.
  4. The result is a key-does-not-exist error.

Example 2 — a number kept as text

  1. The key at insertion was a number.
  2. At access the text of that number was sent.
  3. These are two entirely different values.
  4. Exactly what we saw about representing information.
Before blaming the data: print the keys actually in the dictionary.