
Hold the phone!
On Thu, Jun 28, 2018 at 8:25 AM, Nicolas Rolin nicolas.rolin@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