How to return the best team from a dictionary taking into account the total points and if two teams are tied the goal difference?

Question:

I need to return the name of the best team from several teams inserted in a dictionary taking into account the number of points ("wins"*3 + "draws") and if there are two teams tied I want to return the one with the best goal difference ("scored" – "conceded")
I tried to do it like that but te function returned Barcelona instead of Real Madrid.

def football_league(teams):
    
    best_team = max(teams, key=lambda k: k["wins"]*3 + k["draws"])
    

    if len(best_team)>1:
        best_team = max(teams, key=lambda k: k["scored"] - k["conceded"])
        return best_team["name"]
    
    else:
        return best_team["name"]


la_liga = [
    {
      "name": "Sevilha",
      "wins": 18,
      "loss": 10,
      "draws": 10,
      "scored": 60,
      "conceded": 10,
    },
    {
      "name": "Barcelona",
      "wins": 22,
      "loss": 8,
      "draws": 8,
      "scored": 88,
      "conceded": 20,
    },
    {
      "name": "Real Madrid",
      "wins": 22,
      "loss": 8,
      "draws": 8,
      "scored": 98,
      "conceded": 29,
    },
    {
      "name": "Atletico Madrid",
      "wins": 22,
      "loss": 8,
      "draws": 8,
      "scored": 90,
      "conceded": 30,
    }
]
print(football_league(la_liga))
Asked By: Manuel Carvalhinha

||

Answers:

max() will not return an array of teams, just a single result. What you need is sorting the list according to a tuple of quantities (points, goal_difference). The following code:

la_liga = [
    {
      "name": "Sevilha",
      "wins": 18,
      "loss": 10,
      "draws": 10,
      "scored": 60,
      "conceded": 10,
    },
    {
      "name": "Barcelona",
      "wins": 22,
      "loss": 8,
      "draws": 8,
      "scored": 88,
      "conceded": 20,
    },
    {
      "name": "Real Madrid",
      "wins": 22,
      "loss": 8,
      "draws": 8,
      "scored": 98,
      "conceded": 29,
    },
    {
      "name": "Atletico Madrid",
      "wins": 22,
      "loss": 8,
      "draws": 8,
      "scored": 90,
      "conceded": 30,
    }
]

print(sorted(la_liga, key= lambda t: (t["wins"]*3 + t["draws"],
                                      t["scored"] - t["conceded"]), reverse= True)[0])

will return the true best team:

{'name': 'Real Madrid', 'wins': 22, 'loss': 8, 'draws': 8, 'scored': 98, 'conceded': 29}

(Although, as a Spaniard, I would prefer some other team to win 😉 )

Answered By: Alberto Garcia
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.