Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort list of dictionaries based on multiple values inside the dictionaries

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just specify them like this:

new_list=sorted(teams, key=lambda d: (d['points'], d['wins'], d['names']))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading