Python Finding how a keys value compares to the rest of a dictionary of values


I’m creating a virtual race, and for each frame of the simulation a data file is stored containing each racers distance from the lead point, meaning the racer with the lowest value is winning.

After each race I need to go back to the data for the mid point, and find what race position the eventual winner was in. It’s easy to SEE in the example below the winner (1) was in 3rd position with a distance of 600, but I’m struggling how to do this in Python (There will be 100s of races and many more racers in each race).

RaceDistances = {1:600,2:300,3:450,4:1000,5:750}

>Solution :

We can generate the rankings using .items() to get a list of tuples containing the key-value pairs in the dictionary. Then, we sort by distance using sorted() and the key parameter. We then read off the rankings into a list using a list comprehension.

If you only need to get the rank of one specific player, you can then use .index([<id of player>]) + 1:

race_distances = {1:600,2:300,3:450,4:1000,5:750}

player_ranks = [x for x, _ in sorted(race_distances.items(), key=lambda x: x[1])]

result = player_ranks.index(1) + 1

If you’re going to be looking up the ranks for a lot of players, it is much better to create a dictionary instead, which has faster lookup:

result = {elem: idx + 1 for idx, elem in enumerate(player_ranks)}

In both cases, this prints:


Leave a Reply Cancel reply