Search code examples
pythonjsonsortingjson-api

How to find which item in a JSON list has the greatest value for a given attribute in Python?


I'm using JSON data from the SFG WorldCup API.

What I need to do is to find the most recent goal scored by a given team in a given match. To do that, I need to sort by the value of the attribute key in each element of the array that is the attribute of the away_team_events attribute.

Let me illustrate.

Here's sample JSON for France from the ongoing (at the time of writing) France v Switzerland.

"away_team_events": [
            {
                "id": 276, 
                "type_of_event": "goal", 
                "player": "Giroud", 
                "time": "17"
            }, 
            {
                "id": 277, 
                "type_of_event": "goal", 
                "player": "Matuidi", 
                "time": "18"
            }, 
            {
                "id": 278, 
                "type_of_event": "penalty-wrong", 
                "player": "Benzema", 
                "time": "32"
            }, 
            {
                "id": 279, 
                "type_of_event": "goal", 
                "player": "Valbuena", 
                "time": "40"
            }, 
            {
                "id": 281, 
                "type_of_event": "substitution-in", 
                "player": "Pogba", 
                "time": "63"
            }, 
            {
                "id": 282, 
                "type_of_event": "substitution-in", 
                "player": "Koscielny", 
                "time": "66"
            }, 
            {
                "id": 283, 
                "type_of_event": "goal", 
                "player": "Benzema", 
                "time": "67"
            }
        ]

So what I need to do here is find which "id" attribute is greatest, because that will be the latest goal.

How do I sort by a specific attribute like this?

I've seen this question, but I can't really make sense of the answers.

EDIT: rephrase, sorry for the confusion.

I don't need to necessarily rearrange them, but how do I identify which item in the list has the greatest id, and use that?


Solution

  • Here is my solution, which use the max() function. All I have to do is to tell max how to sort, in this case, by the id field:

    import json
    with open('events.json') as f:
        events = json.load(f)
        event = max(events['away_team_events'], key=lambda ev: ev['id'])
        print event
    

    Output:

    {u'type_of_event': u'goal', u'player': u'Benzema', u'id': 283, u'time': u'67'}
    

    Discussion

    • events is a JSON data with just one key: away_team_events
    • events['away_team_events'] is a list of 7 items. From this list, we are going to select an item with the greatest event ID