I have a list of dictionaries that looks like this:
data = [{'stat3': '5', 'stat2': '4', 'player': '1'}, {'stat3': '8', 'stat2': '1', 'player': '1'}, {'stat3': '6', 'stat2': '1', 'player': '3'}, {'stat3': '3', 'stat2': '7', 'player': '3'}]
And I want to get a nested dictionary whose keys are the value from the key ('player') and whose values ββare dictionaries of aggregated statistics.
The output should be:
{'3': {'stat3': 9, 'stat2': 8, 'player': '3'}, '1': {'stat3': 13, 'stat2': 5, 'player': '1'}}
Below is my code:
from collections import defaultdict result = {} total_stat = defaultdict(int) for dict in data: total_stat[dict['player']] += int(dict['stat3']) total_stat[dict['player']] += int(dict['stat2']) total_stat = ([{'player': info, 'stat3': total_stat[info], 'stat2': total_stat[info]} for info in sorted(total_stat, reverse=True)]) for item in total_stat: result.update({item['player']: item}) print(result)
However, I got the following:
{'3': {'player': '3', 'stat3': 17, 'stat2': 17}, '1': {'player': '1', 'stat3': 18, 'stat2': 18}}
How could I fix this? Or are there other approaches?