Lesson 8 of 10
Lists, dictionaries, tuples, and sets can all contain each other. Real data is almost always shaped this way — a list of records, a record containing a list.
A list of dictionaries
This is the single most common shape you will meet. Think of it as a table: each dictionary is a row, each key a column.
people = [
{"name": "Ada", "age": 36},
{"name": "Grace", "age": 45},
{"name": "Alan", "age": 41},
]
print(people[0])
print(people[0]["name"])
Read people[0]["name"] left to right: take the list, get item 0 (a dictionary), then get its
"name" key.
Looping works exactly as you'd expect:
people = [
{"name": "Ada", "age": 36},
{"name": "Grace", "age": 45},
]
for person in people:
print(f"{person['name']} is {person['age']}")
Note the single quotes inside the f-string — the outer string already uses double quotes, so switching quote style avoids ending the string early.
A dictionary of lists
Useful when one key owns many values.
classes = {
"python": ["Ada", "Grace"],
"rust": ["Alan"],
}
print(classes["python"])
print(classes["python"][1])
classes["rust"].append("Katherine")
print(classes["rust"])
classes["python"][1] is the same left-to-right read: get the list at "python", then item 1.
Going deeper
There is no limit to the nesting, though past two or three levels it gets hard to follow.
company = {
"name": "Acme",
"teams": [
{"name": "backend", "size": 4},
{"name": "design", "size": 2},
],
}
print(company["teams"][0]["name"])
total = 0
for team in company["teams"]:
total += team["size"]
print(total)
Combining with comprehensions
Comprehensions get powerful on nested data — extracting one field from every record is a one-liner:
people = [
{"name": "Ada", "age": 36},
{"name": "Grace", "age": 45},
{"name": "Alan", "age": 41},
]
names = [p["name"] for p in people]
print(names)
older = [p["name"] for p in people if p["age"] > 40]
print(older)
Try it yourself
Loop over the list of dictionaries, print each name, then print how many records there are.
Checkpoint
- A list of dictionaries is the standard shape for a table of records.
- Read
data[0]["key"]left to right, one step at a time. - Nested structures loop and comprehend just like flat ones.
- Watch your quote characters inside f-strings.
Questions about this lesson
Log in to ask a question.