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

Chris Barker chris.barker at noaa.gov
Thu Jun 28 20:11:30 EDT 2018


Hold  the phone!

On Thu, Jun 28, 2018 at 8:25 AM, Nicolas Rolin <nicolas.rolin at tiime.fr>
wrote:

>     student_by_school = defaultdict(list)
>     for student, school in student_school_list:
>         student_by_school[school].append(student)
>
> What I would expect would be a syntax with comprehension allowing me to
> write something along the lines of:
>
>     student_by_school = {group_by(school): student for school, student in
> student_school_list}
>

OK -- I agreed that this could/should be easier, and pretty much like using
setdefault, but did like the single expression thing, so went to "there
should be a way to make a defaultdict comprehension" -- and played with
itertools.groupby (which is really really awkward for this), but then light
dawned on Marblehead:

I've noticed (and taught) that dict comprehensions are kinda redundant with
the dict() constructor, and _think_, in fact, that they were added before
the current dict() constructor was added.

so, if you think "dict constructor" rather than dict comprehensions, you
realize that defaultdict takes the same arguments as the dict(), so the
above is:

defaultdict(list, student_by_school)

which really couldn't be any cleaner and neater.....

Here it is in action:

In [97]: student_school_list
Out[97]:
[('Fred', 'SchoolA'),
 ('Bob', 'SchoolB'),
 ('Mary', 'SchoolA'),
 ('Jane', 'SchoolB'),
 ('Nancy', 'SchoolC')]

In [98]: result = defaultdict(list, student_by_school)

In [99]: result.items()
Out[99]: dict_items([('SchoolA', ['Fred', 'Mary']), ('SchoolB', ['Bob',
'Jane']), ('SchoolC', ['Nancy'])])

So: <small voice> never mind </small voice>

-CHB

-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180628/01b56841/attachment.html>


More information about the Python-ideas mailing list