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.
- A row without
keygoes underNone. - The result must behave like a plain dict: looking up a value that is not in the data raises
KeyError.
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 1
collections.defaultdict(list) creates an empty list the first time a key is used.Hint 2
row.get(key) returns None when the key is missing.Hint 3
Adefaultdict also creates a list when someone reads a missing key. Convert it with dict(...) before returning.Learn the concepts
- Counter, defaultdict and deque · 6 min read. Count, group and keep the last N with the collections module, and the traps in each.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium