Skip to content

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:

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 1Collect per department: a row count and a list (or running sum, count and max) of the salaries that are not None.
Hint 2Keep the two counts apart: count counts rows; the average divides by the number of known salaries.
Hint 3This is SQL's count(*) versus avg(salary), which ignores nulls.

Learn the concepts

More Python problems

All Python problems