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??
Method : Using sorted() + items() + defaultdict() The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
You can add as many items as you like.
values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list.
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With