Real-world data is rarely flat. A single list of numbers or a simple dictionary usually isn't enough to describe the world around you.
Think about your phone's contact book. Each person has a name, a number, and maybe an email address. That looks like one small
Think about your phone's contact book. Each person has a name, a number, and maybe an email address. That looks like one small
dict per person:alice = {'name': 'Alice', 'phone': '555-0123'}But you have many contacts. So the natural shape is a list of dictionaries.List of dicts
contacts = [
{'name': 'Alice', 'phone': '555-0123'},
{'name': 'Bob', 'phone': '555-0456'},
{'name': 'Chloe', 'phone': '555-0789'}
]
print(contacts[0]['name']) # Alicecontacts is a list. contacts[0] grabs the first dict inside it, and then ['name'] pulls out one field from that dict.This pattern of indexing into an index and a key in sequence is called chained indexing. You can chain as many levels deep as you need.
Looping over nested data
contacts = [
{'name': 'Alice', 'phone': '555-0123'},
{'name': 'Bob', 'phone': '555-0456'},
{'name': 'Chloe', 'phone': '555-0789'}
]
for person in contacts:
print(person['name'], '->', person['phone'])
# Alice -> 555-0123
# Bob -> 555-0456
# Chloe -> 555-0789The loop variable
This shape — list of dicts, one per record — shows up everywhere: rows in a database table, items from an API response, log entries.
person is just a dict on each pass. You treat it like any other dict: index into its keys with [...].This shape — list of dicts, one per record — shows up everywhere: rows in a database table, items from an API response, log entries.
Dicts whose values are lists
teams = {
'red': ['Alice', 'Bob'],
'blue': ['Chloe', 'Dana'],
'green': []
}
print(teams['red']) # ['Alice', 'Bob']
print(len(teams['blue'])) # 2Here the top level is a dict, and each value happens to be a list. You reach into it with
The two shapes (list-of-dicts vs. dict-with-list-values) cover most real data you'll meet at this level.
teams[key], then treat that result like any other list — index it, loop over it, measure its length.The two shapes (list-of-dicts vs. dict-with-list-values) cover most real data you'll meet at this level.