

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 7
click for more info
Not enough gems
Cost: 6 gems
1: Aggregation
incomplete
2: Grouping With Dictionaries
incomplete
3: Grouping in Pandas
incomplete
4: Category Type
incomplete
5: Grouping by Multiple Columns
incomplete
6: Multiple Aggregations
incomplete
7: Named Aggregations
incomplete
8: Custom Aggregations
incomplete
9: Pivot Tables
incomplete
10: Pivot Table Aggregations
incomplete
11: Star Schema
incomplete
12: Grain Validation
incomplete
13: Fixing Grain Violations
incomplete
14: Building a Data Model
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
While single-value metrics are useful, many business questions need a breakdown. Total revenue is nice; but total revenue by product is better.
That's where grouping comes in. Instead of calculating one number, you calculate one value per group: sales by region, revenue by product category, errors by error type, etc.
Pandas has a way to group and aggregate data in one step, but we're going to do it "manually" in Python first so you can really understand the concepts.
Let's say you have a list of support tickets and want to know how many tickets came from each channel:
tickets = [
{"channel": "email", "ticket_id": "T-1"},
{"channel": "chat", "ticket_id": "T-2"},
{"channel": "email", "ticket_id": "T-3"},
{"channel": "phone", "ticket_id": "T-4"},
]
# Expected: {"email": 2, "chat": 1, "phone": 1}
You can't use a single accumulator here. You need a dictionary to track each category separately:
def tickets_by_channel(tickets: list[dict]) -> dict[str, int]:
counts = {}
for ticket in tickets:
channel = ticket.get("channel", "unknown")
if channel not in counts:
counts[channel] = 0
counts[channel] += 1
return counts
What if you want the busiest channels? Easy, just sort and slice.
sorted_channels = sorted(counts.items(), key=lambda x: x[1], reverse=True)
top_channels = sorted_channels[:n]
SnackStack's operations team wants to know which kitchen devices are the biggest energy hogs.
Complete the rank_devices_by_energy function. It accepts a list of "reading" dictionaries and a count n, and returns the top n devices as a list of (device_id, total_energy) tuples.
Look up each dictionary field with a default value to handle the missing fields cleanly.