28 Jun
2018
28 Jun
'18
6:23 p.m.
On Thu, Jun 28, 2018 at 10:24 AM Rob Cliffe via Python-ideas < python-ideas@python.org> wrote:
def group_by(iterable, groupfunc, itemfunc=lambda x:x, sortfunc=lambda x:x): # Python 2 & 3 compatible!
D = {} for x in iterable: group = groupfunc(x) D[group] = D.get(group, []) + [itemfunc(x)] if sortfunc is not None: for group in D: D[group] = sorted(D[group], key=sortfunc) return D
The fact that you didn't use ``setdefault`` here, opting for repeatedly constructing new lists via concatenation, demonstrates the need for a built-in or standard library tool that is easier to use. I'll submit a proposal for your review soon.