Home > database >  Finding how a key's value compares to the rest of a dictionary of values
Finding how a key's value compares to the rest of a dictionary of values

Time:03-31

I'm creating a virtual race, and for each frame of the simulation, I have a data file containing each racer's 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 midpoint, 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 hundreds of races and many more racers in each race).

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

CodePudding user response:

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

CodePudding user response:

Counting how many smaller distances there are, then add 1:

print(sum(d < RaceDistances[1]
          for d in RaceDistances.values())   1)
  • Related