首页 > 解决方案 > Python 字典列表聚合值

问题描述

这是一个示例输入:

[{'name':'susan', 'wins': 1, 'team': 'team1'}
{'name':'jack', 'wins':1, 'team':'team2'}
{'name':'susan', 'wins':1, 'team':'team1'}]

期望的输出

[{'name':'susan', 'wins':2, 'team': 'team1'}
{'name':'jack', 'wins':1, 'team':'team2'}]

我有很多字典,只想根据“名称”值添加“胜利”值,并保留“团队”值

我试过用Counter,但结果是

{'name':'all the names added toghther',
 'wins': 'all the wins added toghther'
}

我能够使用defaultdict这似乎工作

result = defaultdict(int)
for d in data:
  result[d['name']] += d['wins'])

但结果是这样的

{'susan': 2, 'jack':1}

在这里它正确添加了值,但没有保留“团队”键

我想我对 defaultdict 及其工作原理感到困惑。

非常感谢任何帮助。

标签: pythonpython-3.xlistdictionarydata-structures

解决方案


你考虑过使用熊猫吗?

import pandas as pd


dicts = [
    {'name':'susan', 'wins': 1, 'team': 'team1'},
    {'name':'jack', 'wins':1, 'team':'team2'},
    {'name':'susan', 'wins':1, 'team':'team1'},
]
agg_by = ["name", "team"]

df = pd.DataFrame(dicts)
df = df.groupby(agg_by)["wins"].apply(sum)

df = df.reset_index()
aggregated_dict = df.to_dict("records")

推荐阅读