Nested Data

A collection can hold other collections. For example, a list can hold dictionaries. This is a common way to store records, with one dictionary for each record.

books = [
    {"title": "Dune", "available": True},
    {"title": "1984", "available": False},
    {"title": "Sula", "available": True},
]

for book in books:
    if book["available"]:
        print(book["title"])

Output:

Dune
Sula

Each time through the loop, book is one dictionary. Then square brackets pick one field from that record, such as book["title"].

To reach a value inside, read from the outside in. books[1]["title"] first picks the second record from the list, and then the title of that record. If a chain like this gets hard to read, store the middle step in a variable with a clear name.

JSON data from web APIs often has this same mix of lists and dictionaries.

In the exercise, print only the team members in the department you read.