You have a list of transactions — each a dict with category and amount — and you want them organized by category: {"Food": [{...}, {...}], "Gas": [{...}]}. How do you transform a flat list into a dict of lists?
Loop through, and for each record append it to a list under its category key. But if the category hasn't been seen yet, the list doesn't exist.
That's the first-time-seen problem. You need an empty list initialized on the first occurrence of each category. Explicit check first:
groups = {}
for item in items:
cat = item["category"]
if cat not in groups:
groups[cat] = []
groups[cat].append(item)Check, initialize if missing, then append. Always safe.
Is there a one-line version using .setdefault() or .get()?
setdefault is built for exactly this — it returns the existing list if the key exists, or inserts an empty list and returns that. You can chain .append() directly:
def group_by_category(items: list) -> dict:
groups = {}
for item in items:
groups.setdefault(item["category"], []).append(item)
return groupsOne line inside the loop — check, init, append all fused into one call.
And if the input list is empty, I just return the empty dict I started with?
Exactly. Initialize groups = {}, never enter the loop body on empty input, return the empty dict. No special case needed — the loop handles zero iterations gracefully.
This is exactly what SQL's GROUP BY does. Whenever I organize records by a category field, this is the pattern.
That's the insight. Python doesn't have a GROUP BY keyword, so you write the pattern explicitly — which means you understand exactly what's happening. Change the key from category to any other field and you've generalized it. Group by status, by type, by date bucket — same pattern.
TL;DR: groups.setdefault(key, []).append(item) — fuse check-init-append into one call.
setdefault — returns existing list or inserts empty and returns itif k not in groups: groups[k] = [] for clarity| Input | Output |
|---|---|
[{"c": "A"}, {"c": "B"}, {"c": "A"}] | {"A": [...,...], "B": [...]} |
[] | {} |
SQL's GROUP BY in Python form — one pass, one dict, linear time.
You have a list of transactions — each a dict with category and amount — and you want them organized by category: {"Food": [{...}, {...}], "Gas": [{...}]}. How do you transform a flat list into a dict of lists?
Loop through, and for each record append it to a list under its category key. But if the category hasn't been seen yet, the list doesn't exist.
That's the first-time-seen problem. You need an empty list initialized on the first occurrence of each category. Explicit check first:
groups = {}
for item in items:
cat = item["category"]
if cat not in groups:
groups[cat] = []
groups[cat].append(item)Check, initialize if missing, then append. Always safe.
Is there a one-line version using .setdefault() or .get()?
setdefault is built for exactly this — it returns the existing list if the key exists, or inserts an empty list and returns that. You can chain .append() directly:
def group_by_category(items: list) -> dict:
groups = {}
for item in items:
groups.setdefault(item["category"], []).append(item)
return groupsOne line inside the loop — check, init, append all fused into one call.
And if the input list is empty, I just return the empty dict I started with?
Exactly. Initialize groups = {}, never enter the loop body on empty input, return the empty dict. No special case needed — the loop handles zero iterations gracefully.
This is exactly what SQL's GROUP BY does. Whenever I organize records by a category field, this is the pattern.
That's the insight. Python doesn't have a GROUP BY keyword, so you write the pattern explicitly — which means you understand exactly what's happening. Change the key from category to any other field and you've generalized it. Group by status, by type, by date bucket — same pattern.
TL;DR: groups.setdefault(key, []).append(item) — fuse check-init-append into one call.
setdefault — returns existing list or inserts empty and returns itif k not in groups: groups[k] = [] for clarity| Input | Output |
|---|---|
[{"c": "A"}, {"c": "B"}, {"c": "A"}] | {"A": [...,...], "B": [...]} |
[] | {} |
SQL's GROUP BY in Python form — one pass, one dict, linear time.
Write `group_by_category(items)` that takes a list of dicts (each with a `"category"` key) and returns a dict mapping each category to a list of items in that category. Preserve input order within each group.
Tap each step for scaffolded hints.
No blank-editor panic.