HomeCourseModule 06 › Nested structures — lists of dicts, dicts of lists

Nested structures — lists of dicts, dicts of lists

Module 06 · Data Structures7 min readBeginner

What you'll learn

  • Build and read nested structures
  • Loop through them cleanly
  • Convert one to a pandas DataFrame

List of dicts — the most common shape

orders = [
    {"id": 101, "customer": "Acme",  "items": ["A1", "B7"],         "total":  450},
    {"id": 102, "customer": "Beta",  "items": ["C3"],               "total":  120},
    {"id": 103, "customer": "Acme",  "items": ["A1", "A1", "B7"],   "total":  780},
]

Reading it

first = orders[0]
print(first["customer"])      # Acme
print(first["items"][0])      # A1
print(orders[2]["items"][-1]) # B7

Looping

for order in orders:
    print(f"Order {order['id']} for {order['customer']}: ${order['total']}")

Aggregating across a list of dicts

# Total revenue
total = sum(o["total"] for o in orders)        # 1350

# Revenue per customer
by_customer = {}
for o in orders:
    cust = o["customer"]
    by_customer[cust] = by_customer.get(cust, 0) + o["total"]

print(by_customer)   # {'Acme': 1230, 'Beta': 120}

And here's why DataFrames are so popular

That last calculation took five lines. With pandas it's one:

import pandas as pd
df = pd.DataFrame(orders)
df.groupby("customer")["total"].sum()

Same answer. Same data. Less code. That's why Module 9 is the turning point in this course.

Key takeaways

  • Real-world data is usually a list of dicts (or a dict of lists).
  • You can do everything with plain Python — it's just verbose.
  • pandas makes the same operations one-liners.

Group by city

Given a list of customer dicts each with city and ltv, build a dict mapping city to total LTV.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.