Course 1.1Lesson 4 of 5
A value of a dictionary can be a list or another dictionary, so a dictionary can hold a record for each key. A lookup with two keys in a row, such as students[name][age], goes down one level at a time. To group items, the value is a list: the first time a key is seen, make an empty list, and then append. A record in a dictionary is easy to read, because each part has a name, such as age and marks. Use get or in at each level to avoid a KeyError.
Try the code and the simulations beside the lesson.
After this lesson you can
A student has a name, an age and some marks. With a list, you would have to remember that position 0 is the name, position 1 the age, and so on. With a dictionary, each part has a name: {"age": 12, "marks": [72, 85, 64]}. This is a record. The code that reads it is easy to read too: student["age"].
The value of a pair can be another dictionary, or a list. So you can keep one record for each student, with the student's name as the key.
A hint for long expressions: read the name of each key aloud, one by one. "The students, Ravi, the marks, the third mark." If you lose your way, print the middle steps: print(students["Ravi"]).
A second very useful pattern: one key, many items. For example, a list of words, grouped by their first letter.
At the end, groups is {"a": ["apple", "avocado", "apricot"], "b": ["banana", "blueberry"], "c": ["cherry"]}. The last loop shows the groups in the order of the letters, with sorted.
Without step 2, the first word of each letter would give a KeyError at the append, because the key and its list do not exist yet.
| Pattern | The value is | The first time |
|---|---|---|
| counting | a number | get(key, 0) gives 0 |
| grouping | a list | make an empty list, then append |
Each bar is the length of one list. The dictionary itself has one key for each letter seen so far.
When data has several levels, draw it first. A school has classes. A class has students. A student has marks. The structure can be a dictionary of dictionaries of lists. But a structure that is too deep is hard to read. If you find yourself writing four levels of brackets, think about whether a simpler form, or a function that hides the lookup, would be clearer.
KeyError in the middle of a long lookup. Check each level: if name in students:.append fails.[] for each new key, made fresh.students["age"] instead of students["Asha"]["age"]."asha" and "Asha" are two records.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
append.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
{"a": {"b": 5}}["a"]["b"]?students?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.