-1

Python 3.11

I was coding a leaderboard and I haven't found a way, how to sort the users, my dictionary is this:

users = {
   "level": {
      "Mark": 4,
      "Steve": 3,
      "Justin": 4,
      "Markus": 2
   }, "xp": {
      "Mark": 43,
      "Steve": 25,
      "Justin": 48,
      "Markus": 32
   }
}

Is there a way to sort the users first by the level, and then if some users have the same level (in that case Mark and Justin), then sort them again by their xp? So it would be like this:

leaderboard = [
   "Justin",
   "Mark",
   "Steve",
   "Markus"
]

Thanks!

  • 2
    `sorted(users['level'], key=lambda n: (users['level'][n], users['xp'][n]), reverse=True)` – deceze Mar 30 '23 at 08:50
  • try this solution - >>> users = { "level": { "Mark": 4, "Steve": 3, "Justin": 4, "Markus": 2 }, "xp": { "Mark": 43, "Steve": 25, "Justin": 48, "Markus": 32 } } >>> leaderboard = sorted(users["level"], key=lambda item: (users['level'][item], users['xp'][item]), reverse=True) >>> leaderboard ['Justin', 'Mark', 'Steve', 'Markus'] – gogo Mar 30 '23 at 09:28

1 Answers1

-1

Edit:
This answer only is valid if the stability of the sort is ensured. This is true since Python 2.2. Please keep this in mind.
For something more generic and an overall better solution, refer to @deceze's comment.

This code should achieve your goal:

users = {
    "level": {
        "Mark": 4,
        "Steve": 3,
        "Justin": 4,
        "Markus": 2
    },
    "xp": {
        "Mark": 43,
        "Steve": 25,
        "Justin": 48,
        "Markus": 32
    }
}

leaderboard = [user for user in users["level"]]

if __name__ == "__main__":
    leaderboard = sorted(leaderboard, key=lambda user: users["xp"][user], reverse=True)
    leaderboard = sorted(leaderboard, key=lambda user: users["level"][user], reverse=True)
    print(leaderboard)

This outputs ['Justin', 'Mark', 'Steve', 'Markus']

What you described is sorting on level as a primary sort and xp as a secondary sort. As a general rule, you'll want to sort following the lowest level of importance first, and make your way up from there.
Here I first sorted with the xp as key, then with the level.

GregoirePelegrin
  • 1,206
  • 2
  • 7
  • 23
  • 1
    This relies on some guarantees about stable sorting. While this may actually work, it's not *generally* reliable (e.g. on older versions of Python). This can and should be done in *one* sorting pass, not two consecutive sorts. – deceze Mar 30 '23 at 08:58
  • You're right, it seems this stability is only guaranteed [since Python 2.2](https://wiki.python.org/moin/HowTo/Sorting/). Thanks for pointing it out! – GregoirePelegrin Mar 30 '23 at 09:03