Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
print(result)

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)}
print(result[1])

In both cases, this prints:

3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading