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

Rhodri James rhodri at kynesim.co.uk
Thu Jun 28 13:07:47 EDT 2018

On 28/06/18 16:25, Nicolas Rolin wrote:
> Hi,
> I use list and dict comprehension a lot, and a problem I often have is to
> do the equivalent of a group_by operation (to use sql terminology).
> For example if I have a list of tuples (student, school) and I want to have
> the list of students by school the only option I'm left with is to write
>      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}
> or any other syntax that allows me to regroup items from an iterable.

Sorry, I don't like the extra load on comprehensions here.  You are 
doing something inherently somewhat complicated and then attempting to 
hide the magic.  Worse, you are hiding it by pretending to be something 
else (an ordinary comprehension), which will break people's intuition 
about what is being produced.

Rhodri James *-* Kynesim Ltd

More information about the Python-ideas mailing list