简体   繁体   中英

iterate through dicts of lists + add up values of identical keys

I have a data structure like this :

[
    { "key" : { "subkey" : "red", "value" : 1 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "blue", "value" : 1 }  },
    { "key" : { "subkey" : "yellow", "value" : 3 }  },
    { "key" : { "subkey" : "blue", "value" : 5 }  },
    { "key" : { "subkey" : "blue", "value" : 8 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "red", "value" : 3 }  },
    { "key" : { "subkey" : "red", "value" : 6 }  },
]

The idea is I would like to iterate through it and when at least 2 "subkeys" are the same, fire off some_event() , which would add up the values from those consecutive objects, until it hits a different "subkey" again.

For example, the first and second dicts should fire off some_event() with values 2+1 added. Then nothing happens with the third (blue) nor fourth (yellow) lines, fifth and sixth (blue) fire off some_event() with values 5+8 , etc.

thanks!

from itertools import groupby

L = [
    { "key" : { "subkey" : "red", "value" : 1 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "blue", "value" : 1 }  },
    { "key" : { "subkey" : "yellow", "value" : 3 }  },
    { "key" : { "subkey" : "blue", "value" : 5 }  },
    { "key" : { "subkey" : "blue", "value" : 8 }  },
    { "key" : { "subkey" : "red", "value" : 2 }  },
    { "key" : { "subkey" : "red", "value" : 3 }  },
    { "key" : { "subkey" : "red", "value" : 6 }  },
]


def some_event(*args):
    print args, sum(args)


for k, g in groupby(L, key=lambda x:x["key"]["subkey"]):
    g = list(g)
    if len(g) > 1:
        some_event(*(i["key"]["value"] for i in g))

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