Daenyth Daenyth - 1 month ago 9
Scala Question

Python equivalent to Scala groupby

I have a list of objects, and I'd like a function that can take that list along with a function operating on the items in that list, and produce a dict with keys from the result of applying that function to the item, and values being a list of items with that key.

Example:

def group_by(iterable: Iterable[A], f: Callable[A, B]) -> Dict[B, List[A]]:
???

lst = [(1,2), (3,4), (1,3)]
result = group_by(lst, lambda i: i[0])
result == {1: [(1,2), (1,3)],
3: [(3,4)]}


itertools.groupby
is close, but I don't want to require that my input be sorted.

Answer

Here's an approach with defaultdict:

from collections import defaultdict
def group_by(iterable, f):
    results = defaultdict(list)
    for x in iterable:
        results[f(x)].append(x)
    return results
Comments