0

I'm trying to sort JSON by high score, but this doesn't work. My JSON:

{"players": [{"test": [{"high_score": 1000}]}, {"test1": [{"high_score": 1200}]}, {"test2": [{"high_score": 3000}]}]}

My Python:

with open('score.json', "r") as json_file:
    data = json.load(json_file)
    json_file.close()
sorted_obj = data
    sorted_obj['players'] = sorted(data['players'], key=lambda x: x['high_score'], reverse=True)
    print(sorted_obj)

Output:

sorted_obj['players'] = sorted(data['players'], key=lambda x: x['high_score'], reverse=True)
KeyError: 'high_score''

I want output to be:

{"players": [{"test2": [{"high_score": 3000}]}, {"test1": [{"high_score": 1200}]}, {"test": [{"high_score": 1000}]}]}

Does anyone know how to solve this? Thanks

2
  • Your JSON structure makes no sense whatsoever. Please don't say that you must use this and cannot change it. Commented Dec 13, 2020 at 11:59
  • if my answer is helpful, please mark it as accepted. Commented Dec 14, 2020 at 8:58

1 Answer 1

1

You don't need to call .close() when you're using a context manager (with ...). The context manager calls .close() for you, that's the whole point.

Your JSON structure is unhelpful in more ways than one. If you cannot change it, this works (I'm not going to explain why, if you have trouble figuring it out then take that as an indication that something is severely wrong with your data structure, because these things shouldn't be this hard.)

with open('score.json', "r") as json_file:
    data = json.load(json_file)

data['players'] = sorted(data['players'], key=lambda p: p[list(p.keys())[0]][0]['high_score'], reverse=True)
print(data)

With a more sensible input data structure, things suddenly become easy.

{"players": [
  {"name": "test", "high_score": 1000},
  {"name": "test1", "high_score": 1200},
  {"name"; "test2", "high_score": 3000}
]}

and

data['players'] = list(sorted(data['players'], key=lambda p: p['high_score'], reverse=True))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, your data structure is much better
@krystof18 The main drawback it has is that you can't index a player by name, i.e. you can't do that_player = data['players']['test1']. But this drawback is super easy to overcome: that_player = next(p for p in data['players'] if p['name'] == 'test1').
@krystof18 Alternatively, building a temporary lookup dict is easy enough as well by_name = {p['name']: p for p in data['players']}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.