python - 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 及其工作原理感到困惑。
非常感谢任何帮助。
解决方案
你考虑过使用熊猫吗?
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")
推荐阅读
- c# - 自定义生产者消费者在使用阻塞收集时随机停止
- flutter - ListView 在 Flutter 中不滚动
- postgresql - 在 PostgreSQL 11.0 中匹配列值并忽略字符串中的特殊字符
- vba - 使用文本作为书签的名称
- c# - 处理缺失的 XML 元素
- microsoft-teams - 使用 GraphApi 在 MS Teams 上自动记录通话
- excel - MS Office 上次更新导致处理 VBA 代码时出现一些奇怪的行为
- amazon-redshift - 加载大型数据集导致连接被拒绝
- android - 为什么我要把 Flutter 中的字符串设为空?
- android - 无法获得足够的预留空间