更新字典列表中的值

3

我有一个字典列表,类似于这样:

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))

......而且它变得混乱了......我是不是完全走错了方向?你能在列表中更改字典的值吗?

谢谢


谢谢大家的帮助,现在我有点犹豫不决该使用哪种方法了 :-) - user4589506
4个回答

3

我认为这是使用Python的pandas库的好例子:

>>> import pandas as pd
>>> dfUsers = pd.DataFrame(users)
>>> dfUsers

    name  score1  score2   team
0  David     100      20   reds
1  David      20      60   reds
2  David      10      70  blues

>>> dfUsers.groupby('team').sum()

       score1  score2
team                 
blues      10      70
reds      120      80

如果你真的想把它放进dict中:

>>> dfRes = dfUsers.groupby('team').sum()
>>> dfRes.columns = ['total1', 'total2']  # if you want to rename columns
>>> dfRes.reset_index().to_dict(orient='records')

[{'team': 'blues', 'total1': 10, 'total2': 70},
 {'team': 'reds', 'total1': 120, 'total2': 80}]

另一种方法是使用itertools.groupby

>>> from itertools import groupby
>>> from operator import itemgetter
>>> users.sort(key=itemgetter('team'))
>>>
>>> res = [{'team': t[0], 'res': list(t[1])} for t in groupby(users, key=itemgetter('team'))]
>>> res = [{'team':t[0], 'total1': sum(x['score1'] for x in t[1]), 'total2': sum(x['score2'] for x in t[1])} for t in res]
>>> res

[{'team': 'blues', 'total1': 10, 'total2': 70},
 {'team': 'reds', 'total1': 120, 'total2': 80}]

如果你真的想要简单的Python:

>>> res = dict()
>>> for x in users:
       if x['team'] not in res:
           res[x['team']] = [x['score1'], x['score2']]
       else:
           res[x['team']][0] += x['score1']
           res[x['team']][1] += x['score2']
>>> res = [{'team': k, 'total1': v[0], 'total2': v[1]} for k, v in res.iteritems()}]
>>> res

[{'team': 'reds', 'total1': 120, 'total2': 80},
 {'team': 'blues', 'total1': 10, 'total2': 70}]

1
你已经非常接近了,你只需要找到一种方法来查找要更新的字典。这是我能想到的最简单的方法。
summary = dict()
for user in users:
   team = user['team']
   if team not in summary:
      summary[team] = dict(team=team,
                           score1=float(user['score1']), 
                           score2=float(user['score2']))
   else:
      summary[team]['score1'] += float(user['score1'])
      summary[team]['score2'] += float(user['score2'])

那么

>>> print summary.values()
[{'score1': 120.0, 'score2': 80.0, 'team': 'reds'},
 {'score1': 10.0, 'score2': 70.0, 'team': 'blues'}]

1

这是我的解决方案,假设需要添加的所有分数都以score开头:

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,}]

totals = {}
for item in users:
    team = item['team']
    if team not in totals:
        totals[team] = {}
    for k,v in item.items():
        if k.startswith('score'):
            if k in totals[team]:
                totals[team][k] += v
            else:
                totals[team][k] = v
print totals

输出:

{'reds': {'score1': 120, 'score2': 80}, 'blues': {'score1': 10, 'score2': 70}}

0

请查看内联注释以获取说明

import pprint

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,}]

scores_by_team = dict()
for user in users:
    if user['team'] not in scores_by_team:
        # Make sure you're gonna have your scores zeroed so you can add the
        # user's scores later
        scores_by_team[user['team']] = {
            'total1': 0,
            'total2': 0
        }
    # Here the user's team exists for sure in scores_by_team
    scores_by_team[user['team']]['total1'] += user['score1']
    scores_by_team[user['team']]['total2'] += user['score2']

# So now, the scores you want have been calculated in a dictionary where the
# keys are the team names and the values are another dictionary with the scores
# that you actually wanted to calculate
print "Before making it a summary: %s" % pprint.pformat(scores_by_team)
summary = list()
for team_name, scores_by_team in scores_by_team.items():
    summary.append(
        {
            'team': team_name,
            'total1': scores_by_team['total1'],
            'total2': scores_by_team['total2'],
        }
    )

print "Summary: %s" % summary

这将输出:

Before making it a summary: {'blues': {'total1': 10, 'total2': 70}, 'reds': {'total1': 120, 'total2': 80}}
Summary: [{'total1': 120, 'total2': 80, 'team': 'reds'}, {'total1': 10, 'total2': 70, 'team': 'blues'}]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接