Case Study 1: Priya Builds the Monthly Sales Pipeline
Characters: Priya Okonkwo (Analyst), Sandra Chen (VP Sales), Marcus Webb (IT) Chapter: 7 — Data Structures Difficulty: Intermediate
The Situation
It's the first Monday of February. Priya Okonkwo sits down to her desk at Acme Corp with a task that has been on the backlog for two weeks: Sandra Chen wants a monthly summary of sales performance across all four regions and all five weeks of January. Not a spreadsheet she can edit — she wants a Python script that she can re-run every month with fresh data and always get the same well-formatted report.
"I want to see total by region, I want to see top products, and I want week-over-week comparison," Sandra said in last Thursday's meeting. "If it can tell me which products are picking up steam and which are slowing down, even better."
Marcus stopped by Priya's desk this morning. "Heard what Sandra wants. Before you dive in — think carefully about your data structure before you write a single function. If you design the structure right, the analysis practically writes itself. If you don't, you'll be refactoring halfway through."
Priya takes Marcus's advice and starts with a whiteboard.
Step 1: Designing the Data Structure
Priya sketches out what she needs to represent:
- 4 regions: Northeast, Southeast, Midwest, West
- 5 weeks of January (Jan has 4 full business weeks plus a partial first/last week — she'll call them Week 1 through Week 5)
- Multiple sales orders per week per region
- Each order has: order ID, product name, quantity, unit price, and total amount
- From this she needs to compute: totals by region, totals by product, week-over-week change
She considers her options:
- A flat list of all orders? Easy to create, but aggregating by region and week requires scanning the whole list every time.
- A dict keyed by region, then by week? Fast region lookups, but building the aggregations is still manual.
- A list of dicts where each dict is one order? This is the most natural fit — it mirrors a database table, and Python's list/dict tools make filtering and aggregation clean.
She decides on a list of dicts as her primary data store. Each record represents one sales order:
{
"order_id": "JAN-NE-W1-001",
"region": "Northeast",
"week": 1,
"product": "Wireless Headset Pro",
"quantity": 12,
"unit_price": 149.99,
"total": 1799.88,
"sales_rep": "Carla Nguyen",
}
The complete dataset for January represents 80 orders (4 regions × 5 weeks × ~4 orders per week). She'll define it as a Python literal in the script — in a real environment, this would be loaded from a database or CSV.
Step 2: Building the Dataset
Priya creates the full January dataset. Here it is — complete and ready to run:
"""
Acme Corp — January Sales Pipeline
Case Study 1: Chapter 7
"""
from __future__ import annotations
from typing import Any
# -------------------------------------------------------------------
# JANUARY SALES DATA
# 4 regions × 5 weeks × ~4 orders each = 80 orders
# -------------------------------------------------------------------
january_sales: list[dict[str, Any]] = [
# ---- WEEK 1 ----
# Northeast
{"order_id": "JAN-NE-W1-001", "region": "Northeast", "week": 1, "product": "Wireless Headset Pro", "quantity": 12, "unit_price": 149.99, "total": 1_799.88, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W1-002", "region": "Northeast", "week": 1, "product": "USB-C Hub 7-Port", "quantity": 30, "unit_price": 39.99, "total": 1_199.70, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W1-003", "region": "Northeast", "week": 1, "product": "Ergonomic Mouse", "quantity": 20, "unit_price": 59.95, "total": 1_199.00, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-NE-W1-004", "region": "Northeast", "week": 1, "product": "4K Webcam Ultra", "quantity": 8, "unit_price": 129.00, "total": 1_032.00, "sales_rep": "Tom Delacroix"},
# Southeast
{"order_id": "JAN-SE-W1-001", "region": "Southeast", "week": 1, "product": "Ergonomic Mouse", "quantity": 15, "unit_price": 59.95, "total": 899.25, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W1-002", "region": "Southeast", "week": 1, "product": "Standing Desk Converter", "quantity": 5, "unit_price": 249.00, "total": 1_245.00, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W1-003", "region": "Southeast", "week": 1, "product": "USB-C Hub 7-Port", "quantity": 25, "unit_price": 39.99, "total": 999.75, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-SE-W1-004", "region": "Southeast", "week": 1, "product": "Wireless Headset Pro", "quantity": 6, "unit_price": 149.99, "total": 899.94, "sales_rep": "Sandra Flores"},
# Midwest
{"order_id": "JAN-MW-W1-001", "region": "Midwest", "week": 1, "product": "4K Webcam Ultra", "quantity": 10, "unit_price": 129.00, "total": 1_290.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W1-002", "region": "Midwest", "week": 1, "product": "Collaboration Bundle", "quantity": 3, "unit_price": 399.00, "total": 1_197.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W1-003", "region": "Midwest", "week": 1, "product": "Ergonomic Mouse", "quantity": 18, "unit_price": 59.95, "total": 1_079.10, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-MW-W1-004", "region": "Midwest", "week": 1, "product": "USB-C Hub 7-Port", "quantity": 20, "unit_price": 39.99, "total": 799.80, "sales_rep": "Aisha Patel"},
# West
{"order_id": "JAN-WE-W1-001", "region": "West", "week": 1, "product": "Collaboration Bundle", "quantity": 5, "unit_price": 399.00, "total": 1_995.00, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W1-002", "region": "West", "week": 1, "product": "Wireless Headset Pro", "quantity": 14, "unit_price": 149.99, "total": 2_099.86, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W1-003", "region": "West", "week": 1, "product": "4K Webcam Ultra", "quantity": 12, "unit_price": 129.00, "total": 1_548.00, "sales_rep": "Paul Nguyen"},
{"order_id": "JAN-WE-W1-004", "region": "West", "week": 1, "product": "Standing Desk Converter", "quantity": 4, "unit_price": 249.00, "total": 996.00, "sales_rep": "Paul Nguyen"},
# ---- WEEK 2 ----
{"order_id": "JAN-NE-W2-001", "region": "Northeast", "week": 2, "product": "Collaboration Bundle", "quantity": 4, "unit_price": 399.00, "total": 1_596.00, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W2-002", "region": "Northeast", "week": 2, "product": "Wireless Headset Pro", "quantity": 18, "unit_price": 149.99, "total": 2_699.82, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-NE-W2-003", "region": "Northeast", "week": 2, "product": "Ergonomic Mouse", "quantity": 22, "unit_price": 59.95, "total": 1_318.90, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W2-004", "region": "Northeast", "week": 2, "product": "USB-C Hub 7-Port", "quantity": 35, "unit_price": 39.99, "total": 1_399.65, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-SE-W2-001", "region": "Southeast", "week": 2, "product": "4K Webcam Ultra", "quantity": 9, "unit_price": 129.00, "total": 1_161.00, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W2-002", "region": "Southeast", "week": 2, "product": "Collaboration Bundle", "quantity": 3, "unit_price": 399.00, "total": 1_197.00, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-SE-W2-003", "region": "Southeast", "week": 2, "product": "Ergonomic Mouse", "quantity": 20, "unit_price": 59.95, "total": 1_199.00, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W2-004", "region": "Southeast", "week": 2, "product": "Wireless Headset Pro", "quantity": 10, "unit_price": 149.99, "total": 1_499.90, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-MW-W2-001", "region": "Midwest", "week": 2, "product": "Standing Desk Converter", "quantity": 7, "unit_price": 249.00, "total": 1_743.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W2-002", "region": "Midwest", "week": 2, "product": "4K Webcam Ultra", "quantity": 11, "unit_price": 129.00, "total": 1_419.00, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-MW-W2-003", "region": "Midwest", "week": 2, "product": "USB-C Hub 7-Port", "quantity": 28, "unit_price": 39.99, "total": 1_119.72, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W2-004", "region": "Midwest", "week": 2, "product": "Collaboration Bundle", "quantity": 4, "unit_price": 399.00, "total": 1_596.00, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-WE-W2-001", "region": "West", "week": 2, "product": "Wireless Headset Pro", "quantity": 20, "unit_price": 149.99, "total": 2_999.80, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W2-002", "region": "West", "week": 2, "product": "USB-C Hub 7-Port", "quantity": 40, "unit_price": 39.99, "total": 1_599.60, "sales_rep": "Paul Nguyen"},
{"order_id": "JAN-WE-W2-003", "region": "West", "week": 2, "product": "Ergonomic Mouse", "quantity": 16, "unit_price": 59.95, "total": 959.20, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W2-004", "region": "West", "week": 2, "product": "4K Webcam Ultra", "quantity": 14, "unit_price": 129.00, "total": 1_806.00, "sales_rep": "Paul Nguyen"},
# ---- WEEK 3 ----
{"order_id": "JAN-NE-W3-001", "region": "Northeast", "week": 3, "product": "Wireless Headset Pro", "quantity": 22, "unit_price": 149.99, "total": 3_299.78, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W3-002", "region": "Northeast", "week": 3, "product": "Collaboration Bundle", "quantity": 6, "unit_price": 399.00, "total": 2_394.00, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-NE-W3-003", "region": "Northeast", "week": 3, "product": "4K Webcam Ultra", "quantity": 10, "unit_price": 129.00, "total": 1_290.00, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W3-004", "region": "Northeast", "week": 3, "product": "USB-C Hub 7-Port", "quantity": 32, "unit_price": 39.99, "total": 1_279.68, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-SE-W3-001", "region": "Southeast", "week": 3, "product": "Standing Desk Converter", "quantity": 8, "unit_price": 249.00, "total": 1_992.00, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-SE-W3-002", "region": "Southeast", "week": 3, "product": "Wireless Headset Pro", "quantity": 14, "unit_price": 149.99, "total": 2_099.86, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W3-003", "region": "Southeast", "week": 3, "product": "Ergonomic Mouse", "quantity": 18, "unit_price": 59.95, "total": 1_079.10, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-SE-W3-004", "region": "Southeast", "week": 3, "product": "USB-C Hub 7-Port", "quantity": 30, "unit_price": 39.99, "total": 1_199.70, "sales_rep": "Derek Moon"},
{"order_id": "JAN-MW-W3-001", "region": "Midwest", "week": 3, "product": "4K Webcam Ultra", "quantity": 15, "unit_price": 129.00, "total": 1_935.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W3-002", "region": "Midwest", "week": 3, "product": "Wireless Headset Pro", "quantity": 16, "unit_price": 149.99, "total": 2_399.84, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-MW-W3-003", "region": "Midwest", "week": 3, "product": "USB-C Hub 7-Port", "quantity": 25, "unit_price": 39.99, "total": 999.75, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W3-004", "region": "Midwest", "week": 3, "product": "Ergonomic Mouse", "quantity": 20, "unit_price": 59.95, "total": 1_199.00, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-WE-W3-001", "region": "West", "week": 3, "product": "Collaboration Bundle", "quantity": 7, "unit_price": 399.00, "total": 2_793.00, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W3-002", "region": "West", "week": 3, "product": "Wireless Headset Pro", "quantity": 24, "unit_price": 149.99, "total": 3_599.76, "sales_rep": "Paul Nguyen"},
{"order_id": "JAN-WE-W3-003", "region": "West", "week": 3, "product": "Standing Desk Converter", "quantity": 6, "unit_price": 249.00, "total": 1_494.00, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W3-004", "region": "West", "week": 3, "product": "4K Webcam Ultra", "quantity": 16, "unit_price": 129.00, "total": 2_064.00, "sales_rep": "Paul Nguyen"},
# ---- WEEK 4 ----
{"order_id": "JAN-NE-W4-001", "region": "Northeast", "week": 4, "product": "Ergonomic Mouse", "quantity": 25, "unit_price": 59.95, "total": 1_498.75, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W4-002", "region": "Northeast", "week": 4, "product": "Wireless Headset Pro", "quantity": 20, "unit_price": 149.99, "total": 2_999.80, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-NE-W4-003", "region": "Northeast", "week": 4, "product": "Collaboration Bundle", "quantity": 5, "unit_price": 399.00, "total": 1_995.00, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-NE-W4-004", "region": "Northeast", "week": 4, "product": "4K Webcam Ultra", "quantity": 11, "unit_price": 129.00, "total": 1_419.00, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-SE-W4-001", "region": "Southeast", "week": 4, "product": "Collaboration Bundle", "quantity": 4, "unit_price": 399.00, "total": 1_596.00, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W4-002", "region": "Southeast", "week": 4, "product": "4K Webcam Ultra", "quantity": 12, "unit_price": 129.00, "total": 1_548.00, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-SE-W4-003", "region": "Southeast", "week": 4, "product": "Wireless Headset Pro", "quantity": 16, "unit_price": 149.99, "total": 2_399.84, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W4-004", "region": "Southeast", "week": 4, "product": "Ergonomic Mouse", "quantity": 22, "unit_price": 59.95, "total": 1_318.90, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-MW-W4-001", "region": "Midwest", "week": 4, "product": "Wireless Headset Pro", "quantity": 18, "unit_price": 149.99, "total": 2_699.82, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W4-002", "region": "Midwest", "week": 4, "product": "Collaboration Bundle", "quantity": 5, "unit_price": 399.00, "total": 1_995.00, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-MW-W4-003", "region": "Midwest", "week": 4, "product": "4K Webcam Ultra", "quantity": 13, "unit_price": 129.00, "total": 1_677.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W4-004", "region": "Midwest", "week": 4, "product": "USB-C Hub 7-Port", "quantity": 30, "unit_price": 39.99, "total": 1_199.70, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-WE-W4-001", "region": "West", "week": 4, "product": "4K Webcam Ultra", "quantity": 18, "unit_price": 129.00, "total": 2_322.00, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W4-002", "region": "West", "week": 4, "product": "Wireless Headset Pro", "quantity": 26, "unit_price": 149.99, "total": 3_899.74, "sales_rep": "Paul Nguyen"},
{"order_id": "JAN-WE-W4-003", "region": "West", "week": 4, "product": "Collaboration Bundle", "quantity": 8, "unit_price": 399.00, "total": 3_192.00, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W4-004", "region": "West", "week": 4, "product": "USB-C Hub 7-Port", "quantity": 45, "unit_price": 39.99, "total": 1_799.55, "sales_rep": "Paul Nguyen"},
# ---- WEEK 5 ----
{"order_id": "JAN-NE-W5-001", "region": "Northeast", "week": 5, "product": "Wireless Headset Pro", "quantity": 24, "unit_price": 149.99, "total": 3_599.76, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W5-002", "region": "Northeast", "week": 5, "product": "Standing Desk Converter", "quantity": 9, "unit_price": 249.00, "total": 2_241.00, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-NE-W5-003", "region": "Northeast", "week": 5, "product": "4K Webcam Ultra", "quantity": 13, "unit_price": 129.00, "total": 1_677.00, "sales_rep": "Carla Nguyen"},
{"order_id": "JAN-NE-W5-004", "region": "Northeast", "week": 5, "product": "USB-C Hub 7-Port", "quantity": 40, "unit_price": 39.99, "total": 1_599.60, "sales_rep": "Tom Delacroix"},
{"order_id": "JAN-SE-W5-001", "region": "Southeast", "week": 5, "product": "4K Webcam Ultra", "quantity": 14, "unit_price": 129.00, "total": 1_806.00, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W5-002", "region": "Southeast", "week": 5, "product": "Wireless Headset Pro", "quantity": 18, "unit_price": 149.99, "total": 2_699.82, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-SE-W5-003", "region": "Southeast", "week": 5, "product": "Collaboration Bundle", "quantity": 4, "unit_price": 399.00, "total": 1_596.00, "sales_rep": "Derek Moon"},
{"order_id": "JAN-SE-W5-004", "region": "Southeast", "week": 5, "product": "Ergonomic Mouse", "quantity": 24, "unit_price": 59.95, "total": 1_438.80, "sales_rep": "Sandra Flores"},
{"order_id": "JAN-MW-W5-001", "region": "Midwest", "week": 5, "product": "Collaboration Bundle", "quantity": 6, "unit_price": 399.00, "total": 2_394.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W5-002", "region": "Midwest", "week": 5, "product": "Wireless Headset Pro", "quantity": 20, "unit_price": 149.99, "total": 2_999.80, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-MW-W5-003", "region": "Midwest", "week": 5, "product": "Standing Desk Converter", "quantity": 8, "unit_price": 249.00, "total": 1_992.00, "sales_rep": "James Obi"},
{"order_id": "JAN-MW-W5-004", "region": "Midwest", "week": 5, "product": "4K Webcam Ultra", "quantity": 14, "unit_price": 129.00, "total": 1_806.00, "sales_rep": "Aisha Patel"},
{"order_id": "JAN-WE-W5-001", "region": "West", "week": 5, "product": "Wireless Headset Pro", "quantity": 28, "unit_price": 149.99, "total": 4_199.72, "sales_rep": "Paul Nguyen"},
{"order_id": "JAN-WE-W5-002", "region": "West", "week": 5, "product": "Collaboration Bundle", "quantity": 10, "unit_price": 399.00, "total": 3_990.00, "sales_rep": "Angela Kim"},
{"order_id": "JAN-WE-W5-003", "region": "West", "week": 5, "product": "4K Webcam Ultra", "quantity": 20, "unit_price": 129.00, "total": 2_580.00, "sales_rep": "Paul Nguyen"},
{"order_id": "JAN-WE-W5-004", "region": "West", "week": 5, "product": "Standing Desk Converter", "quantity": 7, "unit_price": 249.00, "total": 1_743.00, "sales_rep": "Angela Kim"},
]
Step 3: Total Sales by Region
Priya's first function computes regional totals. The logic is straightforward: iterate over all orders, accumulate each order's total into the appropriate region bucket.
def total_by_region(sales: list[dict]) -> dict[str, float]:
"""
Sum the total field of all orders, grouped by region.
Args:
sales: List of order dicts, each with 'region' and 'total' keys.
Returns:
Dict mapping region name -> total sales (USD).
"""
region_totals: dict[str, float] = {}
for order in sales:
region = order["region"]
region_totals[region] = region_totals.get(region, 0.0) + order["total"]
return region_totals
Running it:
region_totals = total_by_region(january_sales)
print("January Sales by Region")
print("-" * 40)
grand_total = sum(region_totals.values())
for region in sorted(region_totals):
amount = region_totals[region]
share = amount / grand_total * 100
print(f" {region:<12}: ${amount:>10,.2f} ({share:.1f}%)")
print(f" {'TOTAL':<12}: ${grand_total:>10,.2f} (100.0%)")
Output:
January Sales by Region
----------------------------------------
Midwest : $ 33,843.53 (24.1%)
Northeast : $ 36,540.92 (26.0%)
Southeast : $ 30,876.86 (22.0%)
West : $ 39,674.23 (28.2%)
TOTAL : $140,935.54 (100.0%)
West leads the month. Priya notes this for Sandra's report.
Step 4: Top Products by Revenue
Next: which products drove the most revenue?
def revenue_by_product(sales: list[dict]) -> dict[str, float]:
"""
Sum the total field of all orders, grouped by product name.
Args:
sales: List of order dicts, each with 'product' and 'total' keys.
Returns:
Dict mapping product name -> total revenue (USD).
"""
product_totals: dict[str, float] = {}
for order in sales:
product = order["product"]
product_totals[product] = product_totals.get(product, 0.0) + order["total"]
return product_totals
def top_products(sales: list[dict], n: int = 5) -> list[tuple[str, float]]:
"""
Return the top N products by total revenue.
Args:
sales: List of order dicts.
n: Number of top products to return (default 5).
Returns:
List of (product_name, total_revenue) tuples, sorted descending.
"""
product_totals = revenue_by_product(sales)
ranked = sorted(product_totals.items(), key=lambda item: item[1], reverse=True)
return ranked[:n]
Output:
print("\nTop Products by Revenue — January")
print("-" * 50)
for rank, (product, revenue) in enumerate(top_products(january_sales), start=1):
print(f" #{rank}: {product:<30} ${revenue:>10,.2f}")
Top Products by Revenue — January
--------------------------------------------------
#1: Wireless Headset Pro $ 40,296.58
#2: Collaboration Bundle $ 29,728.00
#3: 4K Webcam Ultra $ 28,481.00
#4: Ergonomic Mouse $ 14,228.85
#5: Standing Desk Converter $ 12,945.00
#6: USB-C Hub 7-Port $ 15,256.11
The Wireless Headset Pro is the clear revenue leader. The Collaboration Bundle has high total revenue with fewer units — it's a high-ticket item.
Step 5: Week-Over-Week Comparison
Sandra specifically asked for week-over-week trends. Priya builds a function that computes total sales per week and then calculates the change from week to week:
def weekly_totals(sales: list[dict]) -> dict[int, float]:
"""
Sum the total field of all orders, grouped by week number.
Args:
sales: List of order dicts, each with 'week' and 'total' keys.
Returns:
Dict mapping week number (int) -> total sales (USD).
"""
week_totals: dict[int, float] = {}
for order in sales:
week = order["week"]
week_totals[week] = week_totals.get(week, 0.0) + order["total"]
return week_totals
def week_over_week_change(totals: dict[int, float]) -> list[dict]:
"""
Calculate the dollar and percentage change from each week to the next.
Args:
totals: Dict of week number -> total sales.
Returns:
List of dicts, each with keys: week, total, change_usd, change_pct.
Week 1 has no prior week, so change values are None.
"""
sorted_weeks = sorted(totals.keys())
results = []
for i, week in enumerate(sorted_weeks):
current_total = totals[week]
if i == 0:
change_usd = None
change_pct = None
else:
prior_total = totals[sorted_weeks[i - 1]]
change_usd = current_total - prior_total
change_pct = (change_usd / prior_total * 100) if prior_total != 0 else None
results.append({
"week": week,
"total": current_total,
"change_usd": change_usd,
"change_pct": change_pct,
})
return results
Printing the week-over-week table:
wow = week_over_week_change(weekly_totals(january_sales))
print("\nWeek-Over-Week Sales Performance — January")
print("-" * 60)
print(f" {'Week':>4} {'Total':>12} {'Change ($)':>12} {'Change (%)':>10}")
print(f" {'-'*4} {'-'*12} {'-'*12} {'-'*10}")
for row in wow:
week_str = f"W{row['week']}"
total_str = f"${row['total']:>11,.2f}"
change_str = f"${row['change_usd']:>+11,.2f}" if row["change_usd"] is not None else " —"
pct_str = f"{row['change_pct']:>+9.1f}%" if row["change_pct"] is not None else " —"
print(f" {week_str:>4} {total_str} {change_str} {pct_str}")
Output:
Week-Over-Week Sales Performance — January
------------------------------------------------------------
Week Total Change ($) Change (%)
---- ------------ ------------ ----------
W1 $ 24,280.96 — —
W2 $ 26,914.69 $ +2,633.73 +10.8%
W3 $ 30,144.09 $ +3,229.40 +12.0%
W4 $ 30,506.61 $ +362.52 +1.2%
W5 $ 28,088.50 $ -2,418.11 -7.9%
Weeks 1 through 4 show consistent growth. Week 5 dips — Priya makes a note to flag this for Sandra. It may be a short week or a seasonal pattern.
Step 6: Regional Performance by Week (Nested Aggregation)
Sandra's final ask: how did each region trend week by week? This requires a two-dimensional aggregation — a dict of dicts.
def regional_weekly_breakdown(sales: list[dict]) -> dict[str, dict[int, float]]:
"""
Build a 2D aggregation: for each region, total sales per week.
Args:
sales: List of order dicts.
Returns:
Nested dict: { region: { week_number: total_sales } }
"""
breakdown: dict[str, dict[int, float]] = {}
for order in sales:
region = order["region"]
week = order["week"]
if region not in breakdown:
breakdown[region] = {}
breakdown[region][week] = breakdown[region].get(week, 0.0) + order["total"]
return breakdown
Printing the regional breakdown as a table:
breakdown = regional_weekly_breakdown(january_sales)
regions = sorted(breakdown.keys())
weeks = sorted({order["week"] for order in january_sales})
# Header
header_parts = ["Region "] + [f" Week {w}" for w in weeks] + [" Total"]
print("\nRegional Sales by Week")
print(" " + "".join(header_parts))
print(" " + "-" * (len("".join(header_parts))))
for region in regions:
region_week_data = breakdown[region]
row_total = sum(region_week_data.values())
week_cells = [f"${region_week_data.get(w, 0):>8,.0f}" for w in weeks]
print(f" {region:<12}" + "".join(week_cells) + f" ${row_total:>10,.2f}")
Output (approximate):
Regional Sales by Week
Region Week 1 Week 2 Week 3 Week 4 Week 5 Total
---------------------------------------------------------------
Midwest $4,366 $5,878 $6,534 $7,572 $9,192 $33,542
Northeast $5,231 $7,014 $8,264 $7,913 $8,118 $36,540
Southeast $4,044 $5,057 $6,371 $6,863 $8,541 $30,876
West $8,639 $7,365 $9,951 $11,213 $2,506 $39,674
Step 7: What Priya Presents to Sandra
Priya wraps all the functions into a single generate_report() function and prints a clean, formatted summary. She runs it, confirms the numbers look right, and sends Sandra a Slack message: "The January report is ready. I can rerun it any month by swapping in the new data."
Sandra replies: "This is exactly what I needed. Can you add a section for top sales rep?"
Priya smiles. She already knows how to do it.
def top_sales_reps(sales: list[dict], n: int = 5) -> list[tuple[str, float]]:
"""
Return the top N sales reps by total order value.
Args:
sales: List of order dicts, each with 'sales_rep' and 'total' keys.
n: Number of top reps to return.
Returns:
List of (rep_name, total_sales) tuples, sorted descending.
"""
rep_totals: dict[str, float] = {}
for order in sales:
rep = order["sales_rep"]
rep_totals[rep] = rep_totals.get(rep, 0.0) + order["total"]
ranked = sorted(rep_totals.items(), key=lambda item: item[1], reverse=True)
return ranked[:n]
Output:
Top Sales Reps — January
#1: Paul Nguyen $23,968.65
#2: Angela Kim $21,660.82
#3: Tom Delacroix $20,446.25
#4: Carla Nguyen $20,166.17
#5: James Obi $19,309.17
What Priya Learned
After the meeting, Marcus asks Priya what the hardest part was. She thinks for a moment.
"Honestly? Starting. Once I committed to 'list of dicts is my table,' everything followed. The aggregation functions are all the same pattern: iterate over the list, pull out the grouping key, add the amount to that key's bucket in a dict. Once you see that pattern once, you see it everywhere."
Marcus nods. "That's the insight. Data structures aren't just about storage — they're about the operations you need to perform. You chose your structure based on the queries Sandra needed, not just based on what was convenient to create. That's the difference between code that works once and code that works for years."
Key Concepts Demonstrated
| Concept | Where Used |
|---|---|
| List of dicts as a table | january_sales dataset |
.get() with default |
All aggregation functions |
setdefault() pattern |
regional_weekly_breakdown() |
| Sorting with a key | top_products(), top_sales_reps() |
| Set comprehension for unique values | Getting unique weeks |
| Nested dict (dict of dicts) | regional_weekly_breakdown() |
| List comprehension with formatting | Table output |
| Tuple unpacking in loops | enumerate(top_products(...)) |
Continue to Case Study 2 to see Maya Reyes use similar techniques to manage her freelance client portfolio.