Editor

Group By Key

#261 · Python idioms · Intermediate · 55 XP · about 10 min

Write group_by(items, key, value=None) that sorts items into groups. key is a function: items with the same key(item) go into the same group.

Return a dictionary that maps each key to the list of its items, where:

  • the keys appear in the order they were first seen,
  • each list keeps its items in their original order,
  • if value is a function, the lists hold value(item) instead of the items themselves.

Examples

group_by(['apple', 'bean', 'avocado', 'beet', 'corn'], lambda w: w[0])
# returns {'a': ['apple', 'avocado'], 'b': ['bean', 'beet'], 'c': ['corn']}

group_by([1, 2, 3, 4, 5, 6], lambda n: n % 3)
# returns {1: [1, 4], 2: [2, 5], 0: [3, 6]}

people = [('Ana', 'Lisbon'), ('Ben', 'Oslo'), ('Cy', 'Lisbon')]
group_by(people, lambda p: p[1], value=lambda p: p[0])
# returns {'Lisbon': ['Ana', 'Cy'], 'Oslo': ['Ben']}

Constraints

  • Up to 100,000 items; items can be any iterable, including a generator
  • Every key is hashable

Note

itertools.groupby sounds right, but it only groups items that sit next to each other: on the first example it would make two separate 'a' groups.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.