Back to Practice
#0002
Group Records By Key
EasyPython12 min10 XP
Problem
Given a list of records and a key name, return a dictionary where each key value maps to the records with that value.
Why This Matters
Grouping rows is a core data skill. Before pandas groupby, you should understand the plain Python version.
Function Signature
def group_by(records, key):
Examples
Example 1
Inputrecords = [{"team": "A", "score": 10}, {"team": "B", "score": 8}, {"team": "A", "score": 7}], key = "team"
Output{"A": [{"team": "A", "score": 10}, {"team": "A", "score": 7}], "B": [{"team": "B", "score": 8}]}
Both team A records go under "A"; the team B record goes under "B".
Constraints
- Every record contains the requested key.
- Keep records in their original order inside each group.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Group by team
Input[{"team": "A", "score": 10}, {"team": "B", "score": 8}, {"team": "A", "score": 7}], "team"
Expected{"A": [...2 records...], "B": [...1 record...]}
The exact records are preserved; only the outer organization changes.
Hidden Test Categories
Single recordAll records in same groupMany groups with one record each