How to sort a dictionary of dictionaries by their values python

Question:

I have a user dictionary that looks something like this:

{
  user1: {
    userLevel: 1,
    userScore: 2
  },
  user2: {
    userLevel: 5,
    userScore: 16
  },
  user3: {
    userLevel: 3,
    userScore: 14
  }
}

and I need to sort it by values, so that the user with the maximum level is 1st, and if some users have the same level then the one with a better score goes 1st. If some 2 users have the same level and score, any one of them can go first, it doesn’t matter. I tried creating a double loop, but I think there might be a cleaner way to do that, I just can’t figure it out.

Asked By: Black'n'White

||

Answers:

There are already multiple answer on how to order a dictionnary by values. The only thing that’s changing here is that your items are also dictionnaries.

The fonction sorted allows you to sort a dictionnary on a specific key.

What you’re trying to do is to order the dictionnary on a specific key which is in this case the userScore.

Therefore you need to find a way to specify that this is the key on which your sortingis based.

You also need a way to itterate through your dictionnary. This is done with the .items() fonction.

If your big dictionnary is called a, then a.items() will return a list of tuples where each tuple has a key : user_x and a value : the dictionnary.

a.items() = [('user1', {'userLevel': 1, 'userScore': 2}), ('user2', {'userLevel': 5, 'userScore': 16}), ('user3', {'userLevel': 3, 'userScore': 14})]

Now you can itterate through these items and you need to specify that for each item that you parse when you iterate, you need to evaluate whether its key userScore is bigger or lower than the others.

So for each item x ( a tuple in our case ) they key userScore is retrieved with x[1][‘userScore’]

The sorting line of code should look something like this :

a = sorted(a.items(), key = lambda tuple : tuple[1]['userScore']

Answered By: Maxime Bouhadana
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.