How to make a leaderboard?

Say I have data (points) from a couple of users in the dictionary below:

  "John": 10,
  "Ryan": 14,
  "Joe": 33

How would I order the data to make a leaderboard?

From a quick Google search:

scores = {"John": 10, "Ryan": 14, "Joe": 33}
print(sorted(scores.items(), key=lambda a: a[1], reverse=True))

This prints a list of tuples: [('Joe', 33), ('Ryan', 14), ('John', 10)]


Huh? It seems useful, but could you explain what this code does?


But I’ll try

scores.items() returns a dict_items object (dict_items([('John', 10), ('Ryan', 14), ('Joe', 33)])) which you can then pass into the sorted function with a key which uses lambda which takes 1 argument which is the tuple and it returns the second item of the tuple. Then we reverse the list that sorted returns with reverse=True as sorted returns from lowest to highest by default.

After all that you can convert it back to a dict with dict(sorted(scores.items(), key=lambda a: a[1], reverse=True))

I think I subconsciously made that harder to understand, lol…

You can read more about dict.items() here, the sorted function here, and lambda here.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.