Sub topic 3
Reaching into nested data
This chapter assumes you can create lists and dictionaries, index a list with [0], look up a dictionary key with ["key"], and write a simple for loop. You will learn how to read a value from any depth of a nested structure and how to diagnose the errors this produces.
One index per level
A nested structure is read from the outside in. Each pair of square brackets takes one step inward. A list takes an integer position. A dictionary takes a key.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
print(students[1]) # {'name': 'Ben', 'grades': [70, 88, 92]}
print(students[1]["grades"]) # [70, 88, 92]
print(students[1]["grades"][2]) # 92Python evaluates students[1]["grades"][2] from left to right. Each step returns an ordinary object, and the next bracket works on that object.
Reading a path in steps
Long chains can be hard to read and hard to debug. You can split a chain into named steps. The result is the same, and each name documents what you hold at that point.
ben = students[1]
grades = ben["grades"]
print(grades[2]) # 92A chain of three or four brackets is normal. If you find yourself writing six, consider naming the intermediate values.
Negative indexes and other sequences
Everything you know about single-level indexing still applies at each step. Negative indexes count from the end of a list, and strings can be indexed too.
print(students[-1]["grades"][-1]) # 92
print(students[0]["name"][0]) # AReading returns a reference, not a copy
The value a chain returns is the same object that lives inside the structure. If it is a list or dictionary, changing it changes the original.
grades = students[0]["grades"]
grades.append(95)
print(students[0]) # {'name': 'Ana', 'grades': [90, 85, 95]}This is the basis of in-place updates, which the next chapter covers. It also explains the shared-reference problems that come later, so keep it in mind.
Common errors
Each kind of mistake produces a different exception. The exception type tells you which level of the chain is wrong.
| Mistake | Example | Exception |
|---|---|---|
| Key not in the dictionary | `students[1]["grade"]` | `KeyError: 'grade'` |
| Position past the end of the list | `students[5]` | `IndexError: list index out of range` |
| Wrong kind of index for the container | `students["Ben"]` | `TypeError: list indices must be integers or slices, not str` |
| Indexing into `None` or a number | `{"db": None}["db"]["host"]` | `TypeError: 'NoneType' object is not subscriptable` |
The traceback shows the line, but not which bracket in a long chain failed. To find it, print the chain one step at a time, or split it into named variables as shown earlier. The KeyError message does help, because it shows the missing key.
The TypeError cases usually mean your picture of the data is wrong. A value you expected to be a dictionary is a list, or it is None. Print the intermediate value with print(type(value)) and print(value) to see what is there.
Reading data you did not write
When you receive unfamiliar nested data, explore it from the top. Look at the outer type first, then one level at a time.
data = {"user": {"name": "Ana", "roles": ["admin", "dev"]}}
print(type(data)) # <class 'dict'>
print(list(data)) # ['user']
print(list(data["user"])) # ['name', 'roles']
print(data["user"]["roles"][0]) # adminCalling list() on a dictionary gives its keys. This is a quick way to see which keys exist before you write the chain.
Exercise
Given shop = {"name": "Corner", "orders": [{"id": 1, "items": ["tea", "milk"]}, {"id": 2, "items": ["bread"]}]}, write one expression that returns "milk", and one that returns "bread" using a negative index. What exception does shop["orders"][2]["id"] raise?
Show answer
shop["orders"][0]["items"][1] returns "milk". shop["orders"][-1]["items"][-1] returns "bread". The expression shop["orders"][2]["id"] raises IndexError: list index out of range, because orders has only two entries (positions 0 and 1).