Group dictionary key values in python
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'}]
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"))