Your list is already sorted from highest to lowest in terms of points
. Lists are ordered, so you can rely on it to maintain order as you iterate it.
Therefore, you can print your names inside this for
loop:
for team in WorldCup:
print(team['name'])
However, I'm assuming this is ordering is just luck, and you want to handle any possible ordering of teams. If so, we can sort the teams in descending order by points
using sorted()
and reverse=True
.
For the sorting key
, similar to other answers, we can use operator.itemgetter()
. Using itemgetter
instead of lambda
is usually slightly faster, as shown in this answer.
from operator import itemgetter
WorldCup = [
{'name':"Spain", 'points':9},
{'name':"Portugal",'points':7},
{'name':"Iran",'points':6}
]
sorted_teams_desc = sorted(WorldCup, key=itemgetter('points'), reverse=True)
for team in sorted_teams_desc:
print(team['name'])
Output:
Spain
Portugal
Iran