Ptrkcon
Ptrkcon

Reputation: 1505

groupby iterator not adding to list in dictionary comprehension

I have a db query that returns a list. I then do a a dictionary comprehension like so:

results = {product: [g for g in group] for product, group in groupby(db_results, lambda x: x.product_id)}

The problem is that the value of the dictionary is only returning 1 value. I assume this do to the fact that the group is an iterator.

The following returns each item of the group, so I know that they are there:

groups = groupby(db_results, lambda x: x.product_id)
for k,g in groups:
    if k==1001:
        print list(g)

I am trying to get all the values of g in the above in a list whose key is the key of dictionary.

I've tried many variations like:

blah = dict((k,list(v)) for k,v in groupby(db_results, key=lambda x: x.product_id))

but I can't get it right.

Upvotes: 0

Views: 49

Answers (1)

mgilson
mgilson

Reputation: 310059

If you insist on using groupby, then you need to make sure that the input is sorted byt the same key that you group on, however, I think I would suggest that you use defaultdict instead:

from collections import defaultdict
blah = defaultdict(list)
for item in db_results:
    blah[item.product_id].append(item)

Upvotes: 1

Related Questions