Home > database >  How to sort a dictionary of dictionaries by their values python
How to sort a dictionary of dictionaries by their values python

Time:05-19

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. Is there a clean way to do that?

CodePudding user response:

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']

  • Related