Alchemist777 Alchemist777 - 7 months ago 17
Python Question

Group dictionary key values in python

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??

Answer

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
Comments