1

I want to write a program which can print the team with the highest point and then the team with the second highest point and then the third team.

WorldCup=[
    {name:"Spain", points:9},
    {name:"Portugal",points:7},
    {name:"Iran",points:6}
]

I mean I want to put this list into a forloop and get this output:

Spain
Portugal
Iran

I'm not sure if it is possible in a list but it is okay if you can solve it in any possible way.

amir
  • 85
  • 5

3 Answers3

2

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
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1

Here you go:

WorldCup=[
    {'name':"Spain", 'points':9},
    {'name':"Portugal",'points':7},
    {'name':"Iran",'points':6}
]

for team in sorted(WorldCup, key=lambda team: team['points'], reverse=True):
    print(team['name'])

Output:

Spain
Portugal
Iran
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17
1

You have to sort the data by points and print its name only

worldCup = [{'name':"Spain", 'points':9},{'name':"Portugal",'points':7},{'name':"Iran",'points':6}]
    
for item in sorted(worldCup, key=lambda x:x['points'], reverse=True):
  print(item['name'])
azro
  • 53,056
  • 7
  • 34
  • 70