Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

python - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...