Source: Python Morsels

Notes

Exercise is basic hashing: call a function on each item in an iterable and store the result in a dictionary, using the return value of the function as key and a list of items as value.

My solution

1
2
3
4
5
6
7
8
9
def group_by(iter, key_func=lambda x:x):
    result = {}
    for item in iter:
        ret = key_func(item)
        if ret in result:
            result[ret].append(item)
        else:
            result[ret] = [item]
    return result

Provided solution

Uses defaultdict. This collection type will initialize a new key-value pair whenever a missing key is accessed. It does so using the callable passed to it (here, list).

1
2
3
4
5
6
7
from collections import defaultdict

def group_by(iterable, key_func=lambda x: x):
    groups = defaultdict(list)
    for item in iterable:
        groups[key_func(item)].append(item)
    return groups