本文介绍了添加python中的字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想添加个人玩家的得分,并希望显示播放器得分最多的游戏。这是我所指的字典的例子:
I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:
{'match1': {'player1': 57, 'player2': 38},
'match2': {'player3': 9, 'player1': 42},
'match3': {'player2': 41, 'player4': 63, 'player3': 91}}
我尝试了许多解决方案,但无法做出逻辑,以便添加分数来自不同比赛的个人球员。任何帮助将是可观的。感谢提前。
I tried many solutions but unable to make a logic so that it will add the scores of individual players from different matches. Any help will be appreciable. Thanks in advance.
推荐答案
迭代嵌套的字典
并加起来分数到玩家总数的字典。
Iterate over the nested dictionary
and add up scores to a dictionary of player totals.
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}
这篇关于添加python中的字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!