Group by multiple keys and summarize/average values of a list of dictionaries

后端 未结 7 1269
梦谈多话
梦谈多话 2020-11-30 01:03

What is the most pythonic way to group by multiple keys and summarize/average values of a list of dictionaries in Python please? Say I have a list of dictionaries as below:<

7条回答
  •  被撕碎了的回忆
    2020-11-30 01:32

    Like always there are lots of valid solutions, I like the defaultdict one, since I find it easier to understand.

    from collections import defaultdict as df
    food = df(lambda:df(lambda:df(int)))
    for dct in input:  food[dct['transId']][dct['sku']][dct['dept']]=dct['qty']
    output_tupl=[(d1,d2,sum(food[d1][d2][d3] for d3 in food[d1][d2]) )for d1 in food for d2 in food[d1]]
    

提交回复
热议问题