Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build a grouped frequency report with Counter and defaultdict

Group records by a key and produce frequency counts for items using Counter and defaultdict.

Python practice25 minModules & Standard LibraryAdvancedLast updated March 23, 2026

Problem statement

Write group_frequency(records, group_by, count_field=None) that aggregates counts from a list of record dicts. - records: list of dict-like records. - group_by (str): key name used to group records; if missing in a record, group under None. - count_field (str|None): if None, count records per group and return a mapping group -> int. If provided, count occurrences of the value at count_field per group and return mapping group -> dict(value -> count). Return regular Python dicts (not Counters) so the output prints as plain dicts. Use collections.Counter and collections.defaultdict internally to simplify aggregation.

Task

Use collections.Counter and defaultdict to aggregate counts by group, handling missing keys gracefully.

Examples

Count users per language

Input

group_frequency([{'lang':'py','user':'a'},{'lang':'py','user':'b'},{'lang':'js','user':'a'}],'lang','user')

Output

{'py': {'a': 1, 'b': 1}, 'js': {'a': 1}}

Group by lang, then count user occurrences in each language.

Input format

A list of dict records, group_by key, and optional count_field key.

Output format

If count_field is None: dict mapping group -> int. If count_field provided: dict mapping group -> dict mapping item -> count.

Constraints

- Use collections.Counter and collections.defaultdict. - Missing group_by keys map to group None. - Missing count_field keys within a group count as None. - Return plain dicts (convert Counters to dicts) for predictable string representation.

Samples

Sample 1

Input

group_frequency([{'lang':'py'},{'lang':'py'},{'lang':'js'}],'lang')

Output

{'py': 2, 'js': 1}

Counts per group when count_field is omitted.