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:<
I had some extra requirements on top of the original question. I wanted to pass the grouper around and not have to pass around the original order of the fields if you need to reconstruct the grouping key as a dict.
namedtuple() works quite well in that it allows you to sort and use ._asdict()
from collections import namedtuple
def get_grouper(fields):
key = namedtuple('GroupingKey', fields)
def get_key(row):
return key(**{field: row[field] for field in fields})
return get_key
rows = [
{'a': 1, 'b': 1, 'c': 1},
{'a': 1, 'b': 2, 'c': 3},
{'a': 1, 'b': 1, 'c': 2},
{'a': 1, 'b': 0},
{'a': 1, 'b': 2, 'c': 4}
]
grouper = get_grouper(['a','b'])
rows = sorted(rows, key=grouper)
for k, g in groupby(rows, key=grouper):
print(k, list(g))