我有一个字典列表,类似于这样:
users=[{"name": "David", "team": "reds", "score1": 100, "score2": 20,},
{"name": "David", "team": "reds", "score1": 20, "score2": 60,},
{"name": "David", "team": "blues", "score1": 10, "score2": 70,}]
我希望你能够得到一个新的处理过的字典列表,类似于:
summary=[{"team": "reds", "total1": 120, "total2": 80,},
{"team": "blues", "total1": 120, "total2": 80,}]
最好只遍历一次原始数据。我可以创建一个字典,用于保存每个用户键的总值。
summary = dict()
for user in users:
if not user['team'] in summary:
summary[user['team']]=float(user['score1'])
else:
summary[user['team']]+=float(user['score1'])
提供
summary = {'reds': 120,'blues': 10}
我在制作字典列表方面遇到了困难,我能做到的最接近的方式是在第一个团队实例中创建一个字典,然后尝试在后续出现的情况下将其值附加到其上...
summary = []
for user in users:
if any(d['team'] == user['team'] for d in summary):
# append to values in the relevant dictionary
# ??
else:
# Add dictionary to list with some initial values
d ={'team':user['team'],'total1':user['score1'],'total2':user['score2']}
summary.append(dict(d))
......而且它变得混乱了......我是不是完全走错了方向?你能在列表中更改字典的值吗?
谢谢