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

Michael Selik mike at selik.org
Thu Jun 28 20:22:03 EDT 2018


On Thu, Jun 28, 2018 at 5:12 PM Chris Barker via Python-ideas <
python-ideas at python.org> wrote:

> 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'])])
>

Wait, wha...

In [1]: from collections import defaultdict

In [2]: students = [('Fred', 'SchoolA'),
   ...:  ('Bob', 'SchoolB'),
   ...:  ('Mary', 'SchoolA'),
   ...:  ('Jane', 'SchoolB'),
   ...:  ('Nancy', 'SchoolC')]
   ...:

In [3]: defaultdict(list, students)
Out[3]:
defaultdict(list,
            {'Fred': 'SchoolA',
             'Bob': 'SchoolB',
             'Mary': 'SchoolA',
             'Jane': 'SchoolB',
             'Nancy': 'SchoolC'})

In [4]: defaultdict(list, students).items()
Out[4]: dict_items([('Fred', 'SchoolA'), ('Bob', 'SchoolB'), ('Mary',
'SchoolA'), ('Jane', 'SchoolB'), ('Nancy', 'SchoolC')])


I think you accidentally swapped variables there:
student_school_list
vs student_by_school
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180628/e04914cc/attachment.html>


More information about the Python-ideas mailing list