#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:
value is a function, the lists hold value(item) instead of the items themselves.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']}
items can be any iterable, including a generatoritertools.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.
First solves only, ranked by stars and then time.