'I need help sorting a list within a list for a json dictionary
{
"version": 51,
"players": [
{
"ratings": [
{
"hgt": 43,
"stre": 11,
"spd": 49,
"endu": 78,
"pss": 54,
"wst": 44,
"sst": 32,
"stk": 36,
"oiq": 45,
"chk": 16,
"blk": 24,
"fcf": 50,
"diq": 32,
"glk": 11,
"fuzz": 1.5322881555300292,
"ovr": 47,
"pos": "C",
"pot": 47,
"season": 2022,
"skills": [],
"ovrs": {
"C": 47,
"W": 41,
"D": 28,
"G": 1
},
"pots": {
"C": 47,
"W": 41,
"D": 28,
"G": 1
}
}
],
]
}
This may not be a perfect json file as I have just put the main parts I need I want to sort my OVR of several players (not just this one) And I’m having trouble sorting the lists in order to do this.
for player in data["players"]:
ratings = player["ratings"]
sorted_players = sorted(data["players"], key=lambda x: x[“ratings]["ovr"])
This was my attempt but I just get a type error any suggestions?
Solution 1:[1]
It looks like the value for "ratings" is a list so you need to access the first element of it before trying to retrive the value for "ovr":
players_sorted_by_ovr_rating_descendingly = \
sorted(data["players"], key=lambda p: p["ratings"][0]["ovr"], reverse=True)
for player in players_sorted_by_ovr_rating_descendingly:
print(player)
Here is an indented version of your example that highlights this:
data = {
"version": 51,
"players": [
{
"ratings": [
{
"hgt": 43,
"stre": 11,
"spd": 49,
"endu": 78,
"pss": 54,
"wst": 44,
"sst": 32,
"stk": 36,
"oiq": 45,
"chk": 16,
"blk": 24,
"fcf": 50,
"diq": 32,
"glk": 11,
"fuzz": 1.5322881555300292,
"ovr": 47,
"pos": "C",
"pot": 47,
"season": 2022,
"skills": [],
"ovrs": {
"C": 47,
"W": 41,
"D": 28,
"G": 1
},
"pots": {
"C": 47,
"W": 41,
"D": 28,
"G": 1
}
}
]
}
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
