As a teacher, I've found that grouping is one of the most awkward tasks for beginners to learn in Python. While this proposal requires understanding a key-function, in my experience that's easier to teach than the nuances of setdefault or defaultdict. Defaultdict requires passing a factory function or class, similar to a key-function. Setdefault is awkwardly named and requires a discussion of references and mutability. Those topics are important and should be covered, but I'd like to let them sink in gradually. Grouping often comes up as a question on the first or second day, especially for folks transitioning from Excel.
I've tested this proposal on actual students (no students were harmed during experimentation) and found that the majority appreciate it. Some are even able to guess what it does (would do) without any priming.
Thanks for your time,
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:
Thank you for bringing this up. I've been drafting a proposal for a better grouping / group-by operation for a little while. I'm not quite ready to share it, as I'm still researching use cases.
I'm +1 that this task needs improvement, but -1 on this particular solution.