Search code examples
pythondictionarymax

Get max value from nested dictionary return both keys if equal


I have following dictionary

  {
    "match_1":{
        "home_team":2,
        "away_team":1
    },
    "match_2":{
        "home_team":1,
        "away_team":2
    },
    "match_3":{
        "home_team":1,
        "away_team":4}


}

I want to sum home team and away team goals and find which team won in aggregate if both have same score result is draw. I tried converting to tuple and used max with lambda but it fails when result score is same.

required output for current question: winner! away team

if same goals in all matches in aggregate: Draw


Solution

  • Use this tricky way

    d={
        "match_1":{
            "home_team":2,
            "away_team":1
        },
        "match_2":{
            "home_team":1,
            "away_team":2
        },
        "match_3":{
            "home_team":1,
            "away_team":4}
    
    
    }
    score = ((i["home_team"], i["away_team"]) for i in d.values())
    t1,t2 = map(sum,zip(*score))
    [["Away team","Home team"][t1>t2], "Draw"][t1==t2]