'How can I sort a list of dictionaries by a value of the dictionary?
I want to sort this dictionary by points if points equals sort by goal difference, if then equals sort by country name
spain_team = {'name': 'Spain', 'wins': 1, 'loses': 0, 'draws': 2, 'goal difference': 2, 'Goals For': 7, 'Goals Against': 5, 'points': 5}
portogal_team = {'name': 'Portogal', 'wins': 1, 'loses': 1, 'draws': 1, 'goal difference': 0, 'Goals For': 5, 'Goals Against': 5, 'points': 4}
iran_team = {'name': 'Iran', 'wins': 1, 'loses': 1, 'draws': 1, 'goal difference': 0, 'Goals For': 5, 'Goals Against': 5, 'points': 4}
moraco_team = {'name': 'Moraco', 'wins': 1, 'loses': 2, 'draws': 0, 'goal difference': -2, 'Goals For': 4, 'Goals Against': 6, 'points': 3}
x = [iran_team,spain_team,portogal_team,moraco_team]
for i in x:print(i)
Solution 1:[1]
You can achieve this by providing the key argument to the sorted function. You can either provide it as a lambda or use itemgetter like below:
from operator import itemgetter
from pprint import pprint
spain_team = {'name': 'Spain', 'wins': 1, 'loses': 0, 'draws': 2, 'goal difference': 2, 'Goals For': 7, 'Goals Against': 5, 'points': 5}
portogal_team = {'name': 'Portogal', 'wins': 1, 'loses': 1, 'draws': 1, 'goal difference': 0, 'Goals For': 5, 'Goals Against': 5, 'points': 4}
iran_team = {'name': 'Iran', 'wins': 1, 'loses': 1, 'draws': 1, 'goal difference': 0, 'Goals For': 5, 'Goals Against': 5, 'points': 4}
moraco_team = {'name': 'Moraco', 'wins': 1, 'loses': 2, 'draws': 0, 'goal difference': -2, 'Goals For': 4, 'Goals Against': 6, 'points': 3}
x = [iran_team, spain_team, portogal_team, moraco_team]
sorted_list = sorted(x, key=itemgetter('points', 'goal difference', 'name'))
pprint(sorted_list)
If you need the list sorted in reverse order, set the reverse argument:
sorted_in_reverse = sorted(x, key=itemgetter('points', 'goal difference', 'name'), reverse=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan Constantinescu |
