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
x
7
1
result = {}
2
for row in rows:
3
type_id = row['type_id']
4
values = result.get(type_id, [])
5
values.append(row)
6
result[type_id] = values
7
Advertisement
Answer
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:
JavaScript
1
6
1
import collections
2
3
result = collections.defaultdict(list)
4
for row in rows:
5
result[row['type_id']].append(row)
6