Nested data: lists of dictionaries
Read and summarise a list of dictionaries used as records, choosing a list, tuple, set or dictionary for each job.
It opens on
Each of four students is one dictionary, and all four are in the list people. Is people[2]["name"] Bo, Cy, or an error?
Why it matters
Real data, students, orders, readings, comes as many records each with several named parts, and a list of dictionaries holds it; most programs then ask the same few questions of it, a total, a filter, a maximum, a group, and must pick the right container for each.
Good to know first
- Lists: indexing and mutation: people[2] is the item at index 2
- Dictionaries: d[key] reads a value, get gives a default, and counting stores a value under each key
- List comprehensions: [expression for x in items if test] builds a list
- Sets: a set keeps each value once
Step by step
Records in a list
Read a field of a record with people[i][key], loop over the records, and say what len gives at each level.
people[2] is the record at index 2, the third one, since indexes start at 0, and ["name"] is the key inside it. So people[2]["name"] is Cy, which is what the run printed, and this answers the opening question.
the same list as a table
A common mix-up
People["name"] reads every name, or people[2] is the name.
In fact: a list takes an index and gives a record, and only that record takes a key.
Questions about the records
Total, filter, find the maximum and group records with loops over a list of dictionaries.
The total starts at 0 and adds each record's units, 15, 12, 18 and 12, so it prints 57.
A common mix-up
Top = p copies the record.
In fact: It names the same record, so top is a second name for a record that is still in the list.
Choose the structure
Index records by a key in a dictionary, see that it names the same records, and choose list, tuple, set or dictionary for a task.
by_name["Cy"]["units"] printed 18, with no loop, since by_name["Cy"] is the record and ["units"] reads from it.
A common mix-up
A dictionary built from the records holds copies.
In fact: It holds the very same records, so changing one changes the other.
Try it
What does people[3]["name"] + people[0]["name"] give?Answer
"DiAna"
Hint: The last record, then the first
For the cart [{"item": "pen", "qty": 4, "price": 2}, {"item": "ink", "qty": 1, "price": 9}], what total does adding qty times price give?Answer
17
Hint: 4 times 2 is 8, and 1 times 9 is 9
Which structure would you use to look up a customer record by customer id many times, and why?Answer
a dictionary with the id as the key, since each lookup is about one check on average and not a loop
Hint: Lookup by a key
What does people[1]["units"] + people[2]["units"] give?Answer
30, since Bo has 12 units and Cy has 18.
The comprehension keeps p["name"] for the records whose year is 2. What list is that?Answer
['Ana', 'Cy'], the two students in year 2.
