We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Grouping With Dictionaries

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.

The Grouping Challenge

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:

  1. Create an empty dictionary to store results.
  2. For each record, identify the group (the key).
  3. Check if that key exists in the dictionary yet.
  4. Add or update the value for that key.
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

Finding Top Results

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]
  • The .items() method gives us the dictionary's (key, value) pairs as tuples.
  • The key=lambda x: x[1] argument tells sorted() to sort by the second value in each tuple, in our case, ticket count.

Assignment

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.