Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Group Array Objects by Key

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Group Array Objects by Key. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

The J.P. Morgan Access dashboard receives payment records as an array of objects. Implement a function that groups these records by a specified object key, returning every record under the value found at that key.

Use a hash map to achieve linear time complexity. The groups must preserve the original order of records, and the order in which distinct groups first appear must also be preserved.

Formal Specification

Implement group_by_key(items, key).

  • items is a list of dictionaries.
  • key is a string, and every dictionary contains that key.
  • Each key value is hashable, such as a string, integer, or boolean.
  • Return a dictionary mapping each distinct key value to a list of the original dictionaries.
  • Do not modify items or any dictionary inside it.

Constraints

  • 0 <= len(items) <= 10^5
  • 1 <= len(key) <= 50
  • Every object contains the requested key
  • Each grouping value is hashable
  • Do not modify the input list or its dictionaries

Function Signature

def group_by_key(items, key):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output