Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get second largest number from json object in python

I am trying to get the second largest value from a json file. I have managed to get the largest value but not the second value, how would I do this?

this is what I have so far:

    with open('leaderBoard.json') as f:
        events = json.load(f)
        event = max(events['names'], key=lambda ev: ev['points'])
        print(event)

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'PrevStreak': False, 'Streak': 0, 'name': 'kk#7565', 'points': 2000}

and this is my json file:

{
    "names": [

        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "kk#7565",
            "points": 2000
        },

        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "ff#7565",
            "points": 100
        }
    ]
}

any help is great,
Thanks

>Solution :

You could first sort json and then get the value:

with open('leaderBoard.json') as f:
        events = json.load(f)
        events = sorted(events["names"], key=lambda ev: ev["points"])
        event = events[-2]
        print(event)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading