Group rows by a key

easyFoundations~10 min · 7 tests

GROUP BY in SQL, groupby in pandas, a shuffle in Spark. Under all of them sits a dict of lists. Build that dict.

Write group_by(rows, key):

  • rows is a list of dicts.
  • key is the field name to group on.
  • Return a dict that maps each distinct value of row[key] to the list of rows with that value.
  • Keep rows in the order they appeared in the input.
  • Skip rows that don’t have the key at all.
  • An empty input returns {}.
>>> group_by([{"city": "Oslo", "id": 1}, {"city": "Lima", "id": 2}, {"city": "Oslo", "id": 3}], "city")
{'Oslo': [{'city': 'Oslo', 'id': 1}, {'city': 'Oslo', 'id': 3}], 'Lima': [{'city': 'Lima', 'id': 2}]}
Learn the ideaRead the lesson →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run