Dictionaries and Other Collections · practice
Store Many Records in a List
One
book = {
"title": "Kindred",
"category": "novel",
"year": 1979,
}
A
catalog = [
{
"title": "Kindred",
"category": "novel",
"year": 1979,
},
{
"title": "City map",
"category": "reference",
"year": 2026,
},
]
Read the structure from the outside inward:
catalogis a list.Each list item is a dictionary.
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 item has "title" and "year".
If one record uses "name" while the others use "title", the program needs special cases or fails with a
Add another record
Use the list
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
print(catalog[0]["title"])
Work left to right:
catalog[0]returns the first dictionary.["title"]returns the titlefrom 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.

What does this program print?
places = [
{"name": "Kyoto", "country": "Japan"},
{"name": "Lima", "country": "Peru"},
]
print(places[1]["country"])
Task
Add a third catalog
| Key | |
|---|---|
"title" | "Dune" |
"category" | "novel" |
"year" | 1965 |
Then
Kindred (novel)
A Wizard of Earthsea (novel)
Dune (novel)
Records: 3
Use the same three-key shape for every record.