Grade 8 Computer Science · Dictionaries
A key and a value
Why a list is not enough when data is not numbered but named.
One field in the middle, and all the code shifts
A program stores a name, an age and a city for each student and reads them by place: first, second, third. One day someone adds a grade between the name and the age. The program keeps running with no error and prints nonsense. How do you build data so that this simply cannot happen?
A list is excellent when items have an order and a position. But a great deal of real data is not like that: a student has a name, an age and a class — and there is no sense at all in the question “what is the student’s second item”. Such data has a structure of its own, and it is perhaps the most useful structure in programming after the list.
student = {"name": "Ana", "age": 13, "city": "Haifa"}
print(student["name"])
print(student["age"])| The structure | How a value is reached |
|---|---|
| A list | By a position in a sequence |
| A dictionary | By a name you chose |
Why this is more readable
One non-technical difference is worth more here than all the rest. When code asks for the value at a certain position, the reader must remember what sits there — and if someone added a field in the middle, all the numbers shifted and the code is quietly broken. When code asks for the value of “age”, there is nothing to remember and nothing to break: adding a new field touches no existing line. This brings us back exactly to the lesson on variable names — a good name is documentation, and here the names live inside the data itself.
Example 1 — why a position does not fit here
- A student has a name, an age and a class.
- There is no reason for the age to be “the second”.
- The order is entirely arbitrary.
- So a name fits here and a number does not.
Example 2 — adding a field
- A new key is added to the dictionary.
- The other keys did not move.
- No existing line is broken.
- In a list all the numbers would have shifted.