Python Nested Data Exercises: Lists of Dictionaries
Nested data looks complicated until you name each level. A list of dictionaries is just a collection of records; each dictionary is one record with named fields.
Start with one record
A dictionary is a good shape for one record: each key names a field and each value stores its data. Print a single record first so you can see the structure before adding more.
order = {"drink": "latte", "price": 4.5}
print(order["drink"])
print(order["price"])One dictionary, two fields
Read one level at a time
When a value is another dictionary, use a second set of brackets. data["shop"] returns the inner dictionary; ["name"] then reads a field from that dictionary. Do not try to flatten the path in one step.
data = {"shop": {"name": "Corner", "open": True}}
print(data["shop"]["name"])Two levels of keys
Loop over the records
Put dictionaries in a list when you have many records. Loop over the list and read the same key from each record. A list comprehension is useful when you only need one field from every record.
orders = [{"drink": "latte"}, {"drink": "tea"}]
for order in orders:
print(order["drink"])A record collection
Update a nested value
Assignment works through the full path. Select the record, then the key, then assign a new value. Keep the update close to the code that explains why the value changes.
orders = [{"price": 3.0}, {"price": 4.5}]
orders[0]["price"] = 3.5
print(orders[0]["price"])Update one field
Total and filter
A generator expression reads one field from every record, and sum adds the results. Add an if clause when only some records should count. Print the intermediate list when the total looks wrong.
orders = [{"price": 3.0}, {"price": 4.5}, {"price": 2.0}]
print(sum(order["price"] for order in orders))
print([order["price"] for order in orders if order["price"] > 3])Summarise the records
Your practice checklist
- Name the outer collection and the fields inside it.
- Use one pair of brackets per level.
- Loop over records instead of hard-coding indexes.
- Use get or a membership check when a key may be missing.
Common questions
How do I access a value inside a list of dictionaries?
Select the list item first, then the dictionary key: orders[0]["price"]. You can also loop over the list and read the key from each record.
What if a key is missing?
A direct lookup raises KeyError. Use order.get("discount", 0) when a default is appropriate, or check whether the key exists before reading it.
Should nested data be flattened?
Only when a flat shape makes the next operation clearly simpler. Keeping the record structure often makes the code easier to understand.
Practice nested data
12 questions on lists of dictionaries, nested keys, updates, and totals.
Keep reading: