Question

Suppose I have a dict with the contents as follows:

leaderboard = {"James": 4, "Tom": 2, "Tim": 8, "Jim": 2}

How would I go about getting a rank for each name, so that people with the same scores have the same rank?

  Tim: 1
James: 2
  Tom: 3
  Jim: 3
Was it helpful?

Solution 2

You're looking at inversing the mapping from names:ranks to ranks:names. https://stackoverflow.com/a/485368/183948 has your answer.

inv_map = {}
for k, v in leaderboard.items():
    inv_map[v] = inv_map.get(v, [])
    inv_map[v].append(k)

After which, you can sort this inv_map's values to get what you're looking for.

OTHER TIPS

just sort the items by value, loop over them and increase the rank only if the value is strictly smaller than the previous one.

You can use the built in sorted function as well as a lambda function to sort the dictionary by the value instead of the dictionary key. Then we can simply go through a for loop to assign ranks. This code is probably not optimized but it works, you can maybe find out how to optimize the for loop on you own. The ranked dict will hold the peoples rank, you could also put this into a list if you wanted too.

sorted_by_value = sorted(learderboard, key = lambda x: leaderboard[x], reverse = True)

rank = 1
last_value = leaderboard[sorted_by_value[0]]
ranked_dict = dict()
for name in sorted_by_value:
    this_value = leaderboard[name]
    if this_value != last_value:
        rank += 1
    ranked_dict[name] = rank
    last_value = this_value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top