Boopiester
Boopiester

Reputation: 151

How to get key from max with different dictionaries in python?

I'm making a football charts program in python. I am getting the score of 2 teams playing against each other and determining who won. So I am trying to compare the scores and then get the team name of whichever team got the most points. Here is a simplified version of what I am trying to process:

home = {
    "points": 5,
    "team": "New England Patriots"
}

away = {
    "points": 2,
    "team": "Green Bay Packers"
}

Is there a way, other than a bunch of if-statements, to get the team name after determining which team won?

Upvotes: 1

Views: 32

Answers (1)

Riccardo Bucco
Riccardo Bucco

Reputation: 15374

Here is a possible solution:

winner_name = max((home, away), key=lambda d: d['points'])['team']

Here is an example:

>>> home = {"points": 5, "team": "New England Patriots"}
>>> away = {"points": 2, "team": "Green Bay Packers"}
>>> max((home, away), key=lambda d: d['points'])['team']
'New England Patriots'

Upvotes: 2

Related Questions