Group dictionary key values in python

后端 未结 3 1919
执念已碎
执念已碎 2020-12-06 10:24

I have the following dictionary

mylist = [{\'tpdt\': \'0.00\', \'tmst\': 45.0, \'tmdt\': 45.0, \'pbc\': 30, \'remarks\': False, \'shift\': 1, \'ebct\': \'0.         


        
3条回答
  •  悲哀的现实
    2020-12-06 10:45

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

提交回复
热议问题