将重复键的最高值保留在字典中 [英] keep highest value of duplicate keys in dicts

查看:79
本文介绍了将重复键的最高值保留在字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于学校,我正在编写一个用于游戏排名列表的小程序. 为此,我使用字典,将玩家的名称作为键名,将分数作为键值. 将有10场比赛,每场比赛都有一个自动排名系统,我将其打印到文件中. 香港专业教育学院已经设法编码排名系统,但现在面临更大的挑战,我无法解决:

For school i am writing a small program for a rankinglist for a game. I am using dicts for this, with the name of the player as keyname, and the score as keyvalue. there will be 10 games, and each game will have an automatic ranking system which i print to file. ive already managed to code the ranking system, but now im facing a bigger challange which i cannot solve:

我必须进行总体排名,这意味着someplayername可以参加多个比赛并获得多个分数,但是我只需要保留重复项中的最高分数即可.

I have to make an overall ranking, which means someplayername can be in several contests with several scores, but i need to only keep the highest score of a duplicate.

简而言之:我需要一些帮助,以使重复键的值保持最高:

In short: I need some help with keeping the duplicate key with the highest value:

像这样:

dict1 = {"a": 6, "b": 4, "c": 2, "g": 1}
dict2 = {"a": 3, "f": 4, "g": 5, "d": 2}
dictcombined = {'a': 6, 'b': 4, 'c': 2, 'g': 5, 'f': 4, 'd': 2}

普通的合并选项只接受第二个字典,因此取第二个值.

the normal merge option just takes the second dict and thus that value.

提前thnx

推荐答案

您需要具有一个跟踪每个玩家最高得分的功能.如果尚不存在,它将添加一个玩家到总数中;如果更高,则将其添加到总数中. 像这样:

You need to have a function that will keep track of the highest scores for each player. It will add a player to the total if not already there, otherwise adding it if it's higher. Something like this:

def addScores(scores, total):
    for player in scores:
        if player not in total or total[player] < scores[player]:
            total[player] = scores[player]

这篇关于将重复键的最高值保留在字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆