PY-30

Group Values by Key

  • Easy–Medium
  • Dictionaries and Grouping
  • Python

Task

Write group_by_key(records, key_name). records is a list of dictionaries; every record contains key_name, and its value can be used as a dictionary key. Return a dictionary that maps each key value to a list of records having that value.

Create groups in first-key encounter order. Within each group, keep records in their original source order. The records in the result are the original record dictionaries, not rewritten copies. Do not change records or any record.

Example

"math" appears as the first key, and the later "math" record joins that existing list rather than creating a second group. The order shown is the dictionary's insertion order.

Your implementation

Edit solution.py and keep this function name and signature:

Return a new dictionary. Its values must be new lists, while each item in a list must be the corresponding original record dictionary. An empty input returns an empty dictionary. Do not sort the records, print the result, or ask for input.