Medium: Interview Core · Problem 37 of 82

Group By

MediumDictionaries and SetsPython

Write group_by(items, key) where key is a function. It returns a dictionary that maps each value key(item) to the list of items that produced it, in their original order.

group_by(["apple", "bean", "fig"], len) is {5: ["apple"], 4: ["bean"], 3: ["fig"]}.

Understand the problem

Functions can be passed as arguments.

What does list(map(len, ["apple", "bean"])) give? Type the list.

len is a function; map calls it on each item. The same idea works for your parameter key: you can call key(item) inside group_by.

What is key(item) when key is lambda n: n % 3 and item is 7?

7 % 3 is 1. The key function decides which group each item belongs to.

Write the solution

Return the dictionary of lists.

def group_by(items, key):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

For each item, how do you find out its group, and how do you add the item to that group even when the group is new?

Hint 2: the shape of the answer

Loop over the items, compute key(item) and use setdefault(group, []).append(item).

Reflect

Solution

def group_by(items, key):
    groups = {}
    for item in items:
        groups.setdefault(key(item), []).append(item)
    return groups

Another way: defaultdict

from collections import defaultdict

def group_by(items, key):
    groups = defaultdict(list)
    for item in items:
        groups[key(item)].append(item)
    return dict(groups)

What this tests: higher-order functions (a function as a parameter), setdefault, and building groups.

This is itertools.groupby without the catch. itertools.groupby only groups neighbours, so you must sort by the key first. This dictionary version works on any order.

Used everywhere: group orders by customer, log lines by level, files by extension. In pandas it is df.groupby; in SQL, GROUP BY.

Cost: O(n) plus the cost of calling key n times.

What an interviewer might ask next: Make the groups hold only a field of each item, not the item. (Add a second function parameter value, or use a comprehension afterwards.)