[Python-ideas] Allow a group by operation for dict comprehension

Michael Selik mike at selik.org
Thu Jun 28 14:23:49 EDT 2018


On Thu, Jun 28, 2018 at 10:24 AM Rob Cliffe via Python-ideas <
python-ideas at 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180628/b855a2cf/attachment.html>


More information about the Python-ideas mailing list