Hold  the phone!

On Thu, Jun 28, 2018 at 8:25 AM, Nicolas Rolin <nicolas.ro...@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.bar...@noaa.gov
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to