Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中添加字典值_Python_Python 2.7_Python 3.x_Dictionary - Fatal编程技术网

在python中添加字典值

在python中添加字典值,python,python-2.7,python-3.x,dictionary,Python,Python 2.7,Python 3.x,Dictionary,我想添加单个球员的得分,并想显示该球员得分最多的分数。这就是我所指的词典的例子: {'match1': {'player1': 57, 'player2': 38}, 'match2': {'player3': 9, 'player1': 42}, 'match3': {'player2': 41, 'player4': 63, 'player3': 91}} 我尝试了许多解决方案,但无法建立一个逻辑,以便它将不同比赛的个别球员的分数相加。任何帮助都是值得的。提前谢谢 def score(

我想添加单个球员的得分,并想显示该球员得分最多的分数。这就是我所指的词典的例子:

{'match1': {'player1': 57, 'player2': 38},
 'match2': {'player3': 9, 'player1': 42},
 'match3': {'player2': 41, 'player4': 63, 'player3': 91}}
我尝试了许多解决方案,但无法建立一个逻辑,以便它将不同比赛的个别球员的分数相加。任何帮助都是值得的。提前谢谢

def score(match):
    players = {}
    for key in match:
        for player in match[key]:
            if player not in players:
                players[player] =match[key][player]
            else:
                players[player]+=match[key][player]
    return players

快速概述,如果玩家不在新词典中,则创建成员资格并将密钥指向该玩家的分数。否则,将分数添加到该玩家的总数中

迭代嵌套的
字典
,并将分数添加到玩家总数字典中

def find_totals(d):
    total = {}
    for match, results in d.items():
        for player, score in results.items():
            total[player] = total.get(player, 0) + score
    return total
样本输出

>>> d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}}
>>> print find_totals(d)
{'player2': 79, 'player3': 100, 'player1': 99, 'player4': 63}

这是你问题的解决方案

d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}}
players = {}
for key, val in enumerate(d):
    #print val
    for ele,value in enumerate(d[val]):
        #print value
        if value not in players:
            players[value] = d[val][value]
        else:
            players[value] += d[val][value]

print players
highest = 0
highest_player = ""
for key, value in enumerate(players):
    if players[value]>highest:
        highest = players[value]
        highest_player = highest_player.replace(highest_player, value)
print highest_player,players[highest_player]

希望这对您有所帮助。

您尝试过什么?张贴您的解决方案,并解释它的问题所在。另外,请显示您想要获得的输出。您可能对
集合感兴趣。计数器
。可能重复