Skip to content

6. Group Records by Key

Difficulty: Easy · Topic: Core Python & data structures

Write group_by(rows, key): rows is a list of dicts. Return a dict that maps each value of rows[i][key] to the list of rows with that value, in their original order.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

rows = [{'id': 1, 'dept': 'eng'}, {'id': 2, 'dept': 'sales'}, {'id': 3, 'dept': 'eng'}]
group_by(rows, 'dept')

Expected: {'eng': [{'id': 1, 'dept': 'eng'}, {'id': 3, 'dept': 'eng'}], 'sales': [{'id': 2, 'dept': 'sales'}]}

Hints

Hint 1collections.defaultdict(list) creates an empty list the first time a key is used.
Hint 2row.get(key) returns None when the key is missing.
Hint 3A defaultdict also creates a list when someone reads a missing key. Convert it with dict(...) before returning.

Learn the concepts

More Python problems

All Python problems