简体   繁体   中英

groupby iterator not adding to list in dictionary comprehension

I have a db query that returns a list. I then do aa 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM