40. Group and Aggregate without pandas
Difficulty: Medium · Topic: Data wrangling
Write summarize(rows). Each row is a dict with dept and salary (which may be None). Return a dict mapping each department to a dict with:
count: the number of rows in the department, including those with no salary;total,avgandmaxof the known salaries, withavgrounded to 2 decimals. If the department has no known salary,totalis 0 andavgandmaxareNone.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
summarize([
{'dept': 'eng', 'salary': 100},
{'dept': 'eng', 'salary': 50},
{'dept': 'eng', 'salary': None},
{'dept': 'hr', 'salary': 70},
])Expected: {'eng': {'count': 3, 'total': 150, 'avg': 75.0, 'max': 100}, 'hr': {'count': 1, 'total': 70, 'avg': 70.0, 'max': 70}}
Hints
Hint 1
Collect per department: a row count and a list (or running sum, count and max) of the salaries that are notNone.Hint 2
Keep the two counts apart:count counts rows; the average divides by the number of known salaries.Hint 3
This is SQL'scount(*) versus avg(salary), which ignores nulls.Learn the concepts
- Wrangling data without pandas · 5 min read. Parse, flatten, deduplicate, join and aggregate in plain Python, with SQL's null rules.
More Python problems
- Parse Log Lines into Records · Easy
- Reformat Date Strings · Easy
- CSV Rows to Typed Records · Easy
- Flatten Nested JSON · Medium
- Keep the Latest Record per Key · Medium
- Left Join Two Lists of Dicts · Medium
- Merge Overlapping Sessions · Hard
- Schema Validation with a Dead-Letter Queue · Hard