Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build grouped counts from a list of records

Group a list of record dictionaries by one or more keys and compute counts for each grouping.

Python practice30 minList & Dictionary PatternsAdvancedLast updated March 20, 2026

Problem statement

Given a list of dictionaries (records), produce grouped counts based on one or more keys. Implement group_counts(records, keys) where keys may be either a string for a single grouping key or a list/tuple of strings for multiple levels of grouping. Behavior: - For a single key, return a dict mapping each observed key-value to its count. - For multiple keys, return nested dictionaries where the outer key is the first grouping value and the inner structure counts by the remaining keys. - If a record is missing a grouping key, use None as the group value for that level. - Preserve insertion order based on the order records are encountered. Examples: - group_counts([{'city':'NY'},{'city':'NY'},{'city':'SF'}], 'city') -> {'NY': 2, 'SF': 1} - group_counts(records, ['city','dept']) -> {'NY': {'sales': 2, 'eng': 1}, 'SF': {'sales': 1}}

Task

Implement a flexible group_counts function that returns nested count dictionaries for specified grouping keys.

Examples

Single key grouping

Input

group_counts([{'city': 'NY'}, {'city': 'SF'}, {'city': 'NY'}], 'city')

Output

{'NY': 2, 'SF': 1}

Counts occurrences by the 'city' value.

Input format

A Python list of dict records and a grouping key (string or list of strings).

Output format

A Python dict (possibly nested) representing counts for each grouping level.

Constraints

- keys must be provided as a string or as a list/tuple of strings. - Values used for grouping should be treated as-is (including None). Missing keys use None. - Do not use external libraries beyond the Python standard library. - Aim for O(N * K) time where N is number of records and K number of grouping keys.

Samples

Sample 1

Input

group_counts([{'city': 'NY', 'dept': 'sales'}, {'city':'NY','dept':'sales'}, {'city':'SF','dept':'sales'}], ['city','dept'])

Output

{'NY': {'sales': 2}, 'SF': {'sales': 1}}

First group by city, then within each city count by department.