Sort list of dictionaries based on multiple values inside the dictionaries
Question:
I know how to sort a list of dictionaries based on the values, however in this problem I have a couple of conditions that I need the list to sorted based on.
Imagine a list of 4 footbal teams, like in group stage of the Worldcup. For each team we have a dictionary containing team’s wins,loses and points.
Now we need to sort the list first based on the points of each team, if the points are equal then based on wins, and if the wins are equal based on their names. How is it possible with Python?
teams=[{'name':'first_team,'wins':3,'loses':0,'points':9},
{'name':'second_team,'wins':2,'loses':1,'points':6},
{'name':'third_team,'wins':1,'loses':2,'points':3},
{'name':'fourth_team,'wins':0,'loses':3,'points':0}]
Now I know that I can sort the list based on one condition like number of points:
new_list=sorted(teams, key=lambda d:d['points])
But how can I add the other two conditions?
Answers:
Just specify them like this:
new_list=sorted(teams, key=lambda d: (d['points'], d['wins'], d['names']))
I know how to sort a list of dictionaries based on the values, however in this problem I have a couple of conditions that I need the list to sorted based on.
Imagine a list of 4 footbal teams, like in group stage of the Worldcup. For each team we have a dictionary containing team’s wins,loses and points.
Now we need to sort the list first based on the points of each team, if the points are equal then based on wins, and if the wins are equal based on their names. How is it possible with Python?
teams=[{'name':'first_team,'wins':3,'loses':0,'points':9},
{'name':'second_team,'wins':2,'loses':1,'points':6},
{'name':'third_team,'wins':1,'loses':2,'points':3},
{'name':'fourth_team,'wins':0,'loses':3,'points':0}]
Now I know that I can sort the list based on one condition like number of points:
new_list=sorted(teams, key=lambda d:d['points])
But how can I add the other two conditions?
Just specify them like this:
new_list=sorted(teams, key=lambda d: (d['points'], d['wins'], d['names']))