16
votes

I have the following dictionary

mylist = [{'tpdt': '0.00', 'tmst': 45.0, 'tmdt': 45.0, 'pbc': 30, 'remarks': False, 'shift': 1, 'ebct': '0.00', 'tmcdt': '0.00', 'mc_no': 'KA20'}, 
          {'tpdt': '0.00', 'tmst': 45.0, 'tmdt': 45.0, 'pbc': 30, 'remarks': False, 'shift': 1, 'ebct': '0.00', 'tmcdt': '0.00', 'mc_no': 'KA20'}, 
          {'tpdt': '0.00', 'tmst': 55.0, 'tmdt': 55.0, 'pbc': 30, 'remarks': False, 'shift': 1, 'ebct': '0.00', 'tmcdt': '0.00', 'mc_no': 'KA23'}, 
          {'tpdt': '0.00', 'tmst': 55.0, 'tmdt': 55.0, 'pbc': 30, 'remarks': False, 'shift': 1, 'ebct': '0.00', 'tmcdt': '0.00', 'mc_no': 'KA23'}]

I want to get the sum of the key 'tmst' for every dictionary values 'KA20' and 'KA23' in the list of dictionaries.

Could you please have your suggestions on this??

3
What have you tried? What are you having trouble with? Can you loop through each dictionary in the list? Can you check whether a key exists in a dictionary? - John Lyon
yes i can loop through the dictionary and check for the key as well. The value of the key 'mc_no' can become the same for the dictionaries in the list. what i need is to get the sum of the key('tmst') values for these same 'mc_no' values. - Alchemist777

3 Answers

28
votes

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"))
8
votes

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)
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'}]
2
votes

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"]