Given a list of dictionaries, group the records by one field without repeatedly checking whether each group already exists.
Answer
A `defaultdict(list)` is a direct fit because a missing key automatically creates an empty list before the first append. Iterate once through the records and append each record to the list keyed by the selected field. The result is concise, avoids explicit key-existence branches, and runs in O(n) average time for n records.
Strong answer includes
- uses defaultdict(list) or setdefault correctly
- one pass through the records
- explains why explicit key-existence checks are unnecessary
Practical example
Python
Result
Run the code to see the result.
defaultdict(list) creates the group list on first access, so the loop needs only one append statement.
Expected result: ['create user', 'delete user']