Reputation: 670
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:
result = {}
for row in rows:
type_id = row['type_id']
values = result.get(type_id, [])
values.append(row)
result[type_id] = values
Upvotes: 0
Views: 161
Reputation: 1581
btw if you are asking for oneliner comprehension. Not sure about "simplier" part though =)
{type_id:[row for row in rows if row["type_id"] == type_id] for type_id in set(row["type_id"] for row in rows)}
Upvotes: 0
Reputation: 168913
collections.defaultdict
is your friend.
collections.defaultdict(list)
will automatically create new list
s for each key when you index into the defaultdict, so all you need is:
import collections
result = collections.defaultdict(list)
for row in rows:
result[row['type_id']].append(row)
Upvotes: 5