Search code examples
pythonpython-3.xdictionarymergeduplicates

keep highest value of duplicate keys in dicts


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:

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:

like this:

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 in advance


Solution

  • 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]