Practical data workflows
Group and aggregate records
Compute totals by category without losing counts.
Lesson 61 of 63
Reading: about 1 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
A dictionary can hold one total per subject. defaultdict(int) starts a missing subject at zero, which simplifies accumulation.
Worked example
from collections import defaultdict
rows = [("Python", 20), ("SQL", 25), ("Python", 30)]
totals = defaultdict(int)
for subject, minutes in rows:
totals[subject] += minutes
print(dict(totals)){'Python': 50, 'SQL': 25}Why this works
The loop adds each duration to its subject’s running total. Dictionary insertion order follows the first occurrence of each subject in modern Python.
Another case
from collections import Counter
print(dict(Counter(["Python", "SQL", "Python"]))){'Python': 2, 'SQL': 1}Practice
What are the totals after adding ("SQL", 5)?
Check the practice result
Reveal answer
Python remains 50; SQL becomes 30.
Try another case
How would you count sessions per subject instead of adding minutes?
Check your answer
Reveal answer
Use totals[subject] += 1, or Counter(subject for subject, _ in rows). For the lesson rows that gives Python 2 and SQL 1.
Your progress
Reveal the check answer or reach the end to complete this lesson.