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.
- Writing to an existing key adds a second value — It replaces the old one, with no error. Ask: what is the dictionary’s length against the number of items?
- A key that does not exist returns empty — It gives an immediate error. Ask: did I check the key is there?
- A dictionary has an order that can be relied on — It has no meaningful “first key”. Ask: does my code assume any order?
- Anything can be used as a key — The key must be a value that does not change. Ask: can this value change later?
- A dictionary is always faster than a list — It is fast at lookup by key alone. Ask: which question am I asking of the data?
- A dictionary can be changed while going over it — Items are skipped, and sometimes there is an error. Ask: am I changing a structure I am going over?
Example 1 — a key that looks identical and is not
- At insertion the key was written with no space.
- At access the same key was written with a space.
- To the eye they are identical; to the computer not.
- The result is a key-does-not-exist error.
Example 2 — a number kept as text
- The key at insertion was a number.
- At access the text of that number was sent.
- These are two entirely different values.
- Exactly what we saw about representing information.