在python中汇总嵌套字典值

时间:2017-02-23 16:02:11

标签: python dictionary

我们在两级词典中代表一系列匹配的击球手,如下所示:

compile

每个比赛由一个字符串标识,每个玩家也是如此。分数都是整数。与匹配相关联的名称不是固定的(此处为{'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91} match1match2),也不是播放器的名称。玩家不需要在所有比赛中记录得分

定义一个Python函数match3,它读取此表单的字典d并标识总得分最高的玩家。您的函数应该返回一对orangecap(d),其中(playername,topscore)是一个字符串,得分最高的玩家的名称,playername是一个整数,总分为topscore

3 个答案:

答案 0 :(得分:1)

总结数据并选择最高值通常可以使用collections.Counter()完成,如下所示:

def orangecap(d):
    from collections import Counter
    return sum((Counter(game) for game in d.values()), Counter()).most_common(1)[0]

答案 1 :(得分:0)

不如Rob的答案那么漂亮,但不需要任何进口:

def orangecap(d):
    first_run = 1
    for match in d:
        for player in d[match]:
            if first_run == 1:
                first_run = 0
                topscore = d[match][player]
                playername = d[match]
            elif d[match][player] > topscore:
                topscore = d[match][player]
                playername = player

    return [playername, topscore]

答案 2 :(得分:0)

这是一个有目的(!)冗长而不是特别优雅的解决方案,它只使用相当基本的数据结构,try / except,for循环和条件。对于初学者,我认为这可能更有助于遵循所有步骤的逻辑,即正在发生的事情的方式和原因。我使用了描述性变量名来使其易于理解。如果两个或更多玩家具有相同的总分,则以下代码也将起作用:

game = {'match1': {'player1': 57, 'player2': 38},
        'match2': {'player3': 9, 'player1': 42},
        'match3': {'player2': 41, 'player4': 63, 'player3': 91},
        'match4': {'player1': 1}}


def orangecap(matches):
    players_and_scores = {}
    top_players_and_scores = []

    for match in matches:
        for player, score in matches[match].items():
            try:  # if key already exists
                players_and_scores[player] += score
            except:  # if key does not exist yet
                players_and_scores[player] = score

    # all players and their total stores:
    # print(players_and_scores)

    for player, score in players_and_scores.items():
        if score == max(players_and_scores.values()):
            top_players_and_scores.append((player, score))

    # return all top players (can be more than one)
    # and their total scores:
    return top_players_and_scores

print(orangecap(game))

输出:

[('player3', 100), ('player1', 100)]

注意我将密钥match4添加到字典中,以便让两个玩家拥有相同的总分。

Robᵩ的解决方案更加简洁和优雅,如果您能够遵循它的功能并且允许使用collections.Counter(),则建议使用它。但是,它只返回得分最高的一名球员,因此可能需要进行一些调整。

相关问题