[英]Python list of dictionaries aggregate values
Here is an example input:这是一个示例输入:
[{'name':'susan', 'wins': 1, 'team': 'team1'}
{'name':'jack', 'wins':1, 'team':'team2'}
{'name':'susan', 'wins':1, 'team':'team1'}]
Desired output所需 output
[{'name':'susan', 'wins':2, 'team': 'team1'}
{'name':'jack', 'wins':1, 'team':'team2'}]
I have lots of the dictionaries and want to only add, the 'win' value, based on the 'name' value, and keep the 'team' values我有很多字典,只想根据“名称”值添加“胜利”值,并保留“团队”值
I've tried to use Counter
, but the result was我试过使用
Counter
,但结果是
{'name':'all the names added toghther',
'wins': 'all the wins added toghther'
}
I was able to use defaultdict
which seemed to work我能够使用似乎有效的
defaultdict
result = defaultdict(int)
for d in data:
result[d['name']] += d['wins'])
but the results was something like但结果是这样的
{'susan': 2, 'jack':1}
Here it added the values correctly but didn't keep the 'team' key在这里它正确添加了值,但没有保留“团队”键
I guess I'm confused about defaultdict and how it works.我想我对 defaultdict 及其工作原理感到困惑。
any help very appreciated.非常感谢任何帮助。
Did you consider using pandas?您是否考虑过使用 pandas?
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.