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

后端 未结 7 1228
梦谈多话
梦谈多话 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:35

    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))
    
    0 讨论(0)
提交回复
热议问题