Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresJuniorCommonPractical

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

Group test results by suite
Python
editable · browser sandbox
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']

#dict#collections#grouping

Sources

collections — Container datatypesPython Software Foundation · deque, defaultdict, Counter, namedtuple and ChainMap semantics