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
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:
import collections result = collections.defaultdict(list) for row in rows: result[row['type_id']].append(row)