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:
{'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
CodePudding user response:
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)
CodePudding user response:
Assuming 0 is the minimal number of points,
with open('leaderBoard.json') as f:
events = json.load(f)
max_points = max(events['names'], key=lambda ev: ev['points'])
2nd_points = max(events['names'], key=lambda ev: ev['points'] if ev['points'] < max_points else 0)
print(2nd_points)