Daenyth Daenyth - 21 days ago 4
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.


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)]}

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


Here's an approach with defaultdict:

from collections import defaultdict
def group_by(iterable, f):
    results = defaultdict(list)
    for x in iterable:
    return results