Skip to content
Advertisement

Reduce list to a dictionary of lists

I’m pulling a bunch of rows out of my database, many of which share a similar ID. I want to group the ones with the same ID into a list and generate a map that maps from the ID to the list of results. I have the following code, but it seems like there must be a simpler way of doing it with reduce or dictionary comprehension:

JavaScript

Advertisement

Answer

collections.defaultdict is your friend.

collections.defaultdict(list) will automatically create new lists for each key when you index into the defaultdict, so all you need is:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement