Python equivalent to Scala groupby -


i have list of objects, , i'd function can take list along function operating on items in list, , produce dict keys result of applying function item, , values being list of items 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 close, don't want require input sorted.

here's approach defaultdict:

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

Comments