Sub topic 2
Common ways to nest data
This chapter assumes you can create lists and dictionaries, index into them, and write simple for loops and functions. It covers the four shapes you will meet most often when data is nested, and how to choose between them. Later chapters cover reading, changing, and copying these shapes.
What nesting means
Nesting means storing a container inside another container. A list can hold dictionaries, a dictionary can hold lists, and so on. Python places no limit on the depth, and the containers can be mixed freely.
The shape you pick should match the questions you will ask of the data. Ask first: "Do I look things up by position, or by name?"
The four common shapes
| Shape | Outer container | Inner container | Typical use |
|---|---|---|---|
| List of dicts | list | dict | Records, such as rows from a table |
| Dict of lists | dict | list | Groups, such as items under a label |
| Dict of dicts | dict | dict | Records looked up by a key |
| List of lists | list | list | Grids and tables of plain values |
List of dictionaries
Each dictionary describes one record, and the list keeps the records in order. This is the shape of most data returned by web APIs and database queries.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
print(students[1]["name"]) # Ben
print(len(students)) # 2Use it when you have many items with the same fields and you mostly process them in order.
Dictionary of lists
Each key names a group, and its list holds the members of that group.
words_by_letter = {
"a": ["apple", "avocado"],
"b": ["banana", "blueberry"],
}
print(words_by_letter["a"][1]) # avocadoUse it when you need to jump straight to a group by its label.
Dictionary of dictionaries
The outer keys identify records, and each inner dictionary holds that record's fields. The inventory example below groups counts by category and then by item name.
inventory = {
"fruit": {"apple": 3, "pear": 0},
"veg": {"kale": 5},
}
print(inventory["fruit"]["apple"]) # 3Use it when each record has a natural unique key, such as a username or an ID. Lookup by key is fast, while finding a record in a list of dictionaries means scanning the list.
List of lists
Each inner list is a row. This is how you represent a grid, a matrix, or a small table of values with no field names.
grid = [
[1, 2, 3],
[4, 5, 6],
]
print(grid[1][2]) # 6Use it when position carries the meaning, such as row and column.
Mixing shapes
Real data often combines these shapes. The students example above is a list of dictionaries where one value is itself a list. Each level uses whichever container suits it.
To describe any structure, read it from the outside in. students is a list of dictionaries, and the grades value inside each dictionary is a list of numbers.
Choosing a shape
Pick the outer container by how you find things:
- If you find items by position or process them in order, use a list.
- If you find items by a name or ID, use a dictionary.
Then pick the inner container the same way. Inner lists suit collections without names, and inner dictionaries suit records with named fields.
A common mistake is using a list of lists for records, such as ["Ana", 90, 85]. You then have to remember that index 0 is the name and index 1 is the first grade. A dictionary with named keys is easier to read and harder to misuse.
Checking your understanding
Exercise
You are storing the books in a library. Each book has a title, an author, and a list of genres. You also need to find a book quickly by its ISBN. Which nesting shape fits, and what would one entry look like?
Show answer
A dictionary of dictionaries. The outer keys are ISBNs, so lookup is direct. Each inner dictionary holds the fields, and the genres value is a list. For example: {"978-0-06-112008-4": {"title": "To Kill a Mockingbird", "author": "Harper Lee", "genres": ["fiction", "classic"]}}. A list of dictionaries would also store the data, but finding one ISBN would mean scanning the whole list.
Exercise
What shape is {"mon": [9, 11], "tue": [10]}, and what does data["mon"][1] return?
Show answer
It is a dictionary of lists. data["mon"][1] returns 11, the second item in the list stored under "mon".