Home > Software engineering >  How can I sort a nested dict by multiple criteria for values and keys?
How can I sort a nested dict by multiple criteria for values and keys?

Time:12-20

I have a nested dict in Python that I want to sort.

In the first step I want it to be sorted by "points".
If all the "points" are equal, use "wins".
If "points" and "wins" are equal, it should be sorted by the team names like "Brazil", "Morocco", etc.

My dict is

list_of_team = {
    "Brazil": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4},
    "Spain": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4},
    "Portugal": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4},
    "Morocco": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4}
}

The output should look like this:

Brazil  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4

Morocco  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4 

Portugal  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4

Spain  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4

CodePudding user response:

sorted(list_of_team, key= lambda x : list_of_team[x].get("points"))

CodePudding user response:

If you want to sort by "points" and "wins" in descending order and by team name in lexicographic order:

out = sorted(list_of_team, key= lambda x : (-list_of_team[x].get("points"), -list_of_team[x].get("wins"), x))
  • Related