I have the following dictionary
mylist = [{\'tpdt\': \'0.00\', \'tmst\': 45.0, \'tmdt\': 45.0, \'pbc\': 30, \'remarks\': False, \'shift\': 1, \'ebct\': \'0.
Here's a code that doesn't require mylist
to be sorted by "mc_no"
key:
from collections import defaultdict
sums = defaultdict(int) # key -> sum
for d in mylist:
sums[d["mc_no"]] += d["tmst"]
You can use itertools.groupby
:
>>> for key, group in itertools.groupby(mylist, lambda item: item["mc_no"]):
... print key, sum([item["tmst"] for item in group])
...
KA20 90.0
KA23 110.0
Note that for groupby
to work properly, mylist
has to be sorted by the grouping key:
from operator import itemgetter
mylist.sort(key=itemgetter("mc_no"))
First you needs to sort that list of dictionaries..using following code.. Ex.
animals = [{'name':'cow', 'size':'large'},{'name':'bird', 'size':'small'},{'name':'fish', 'size':'small'},{'name':'rabbit', 'size':'medium'},{'name':'pony', 'size':'large'},{'name':'squirrel', 'size':'medium'},{'name':'fox', 'size':'medium'}] import itertools from operator import itemgetter sorted_animals = sorted(animals, key=itemgetter('size'))
then you use following code
for key, group in itertools.groupby(sorted_animals, key=lambda x:x['size']): print key, print list(group)
After you will get following result...
large [{'name': 'cow', 'size': 'large'}, {'name': 'pony', 'size':'large'}] medium [{'name': 'rabbit', 'size': 'medium'}, {'name': 'squirrel', 'size':'medium'}, {'name': 'fox', 'size': 'medium'}] small [{'name': 'bird', 'size': 'small'}, {'name': 'fish', 'size': 'small'}]