0%

Dictionaries and Other Collections · practice

Store Many Records in a List

One models one record:

book = {
    "title": "Kindred",
    "category": "novel",
    "year": 1979,
}

A can hold many records in order:

catalog = [
    {
        "title": "Kindred",
        "category": "novel",
        "year": 1979,
    },
    {
        "title": "City map",
        "category": "reference",
        "year": 2026,
    },
]

Read the structure from the outside inward:

  1. catalog is a list.

  2. Each list item is a dictionary.

  3. Each dictionary uses the same keys to describe one item.

Keep a consistent shape

A list of records is easiest to use when every record has the same required keys.

for item in catalog:
    print(f"{item['title']} ({item['year']})")

The can trust that every item has "title" and "year".

If one record uses "name" while the others use "title", the program needs special cases or fails with a . Consistent data makes the code simpler.

Add another record

Use the list you already know:

catalog.append(
    {
        "title": "Trail guide",
        "category": "reference",
        "year": 2024,
    }
)

The list changes by one item. The dictionaries already inside it are unchanged.

Reach one field

You can combine a list and a :

print(catalog[0]["title"])

Work left to right:

  1. catalog[0] returns the first dictionary.

  2. ["title"] returns the title from that dictionary.

This chained form is useful when the position is known. A loop is better when you need every record.

Now inspect the complete shape below. Follow the lookup from the outer list, through index 0, and then through the "title" key. Every label in the picture now names an operation you have met.

A catalog list contains two consistently shaped dictionaries; catalog index zero selects the first record and title selects its Kindred value.

What does this program print?

places = [
    {"name": "Kyoto", "country": "Japan"},
    {"name": "Lima", "country": "Peru"},
]

print(places[1]["country"])

Task

Add a third to the catalog :

Key
"title""Dune"
"category""novel"
"year"1965

Then through every record and print:

Kindred (novel)
A Wizard of Earthsea (novel)
Dune (novel)
Records: 3

Use the same three-key shape for every record.