简体   繁体   中英

python: list of dict to groupby similar key elements

I have a list of dict:

xList =  [{491: 551}, {598: 60}, {47: 130}, {47: 451}, {47: 792}, {47: 599}, {47: 590}]

I am trying to groupby similar key values to get:

res =  [{ 491 : [551], 598: [60], 47: [130, 451, 792, 599, 590}]

I tried:

from collections import defaultdict

v = defaultdict(list)

for key, value in sorted(xList.items()):
    v[key].append(value)

but this expects a flat dict not a list of dict

Then you do a nested iteration.

Iterate over the list, then iterate over the (key, value) of the dict.

rslt = {}
for i in xList:
    for k, v in i.items():
        rslt.setdefault(k, []).append(v)

Using defaultdict ,

from collections import defaultdict

xList =  [{491: 551}, {598: 60}, {47: 130}, {47: 451}, 
          {47: 792}, {47: 599}, {47: 590}]

values = defaultdict(list)

for x in xList:
    k, v = tuple(*x.items())
    values[k].append(v)

defaultdict(<class 'list'>, {491: [551], 598: [60], 47: [130, 451, 792, 599, 590]})

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