【问题标题】:Sorting JSON file in python by value in JSON按JSON中的值对python中的JSON文件进行排序
【发布时间】:2023-03-30 07:17:01
【问题描述】:

我正在尝试按高分对 JSON 进行排序,但这不起作用。 我的 JSON:

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

我的 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)

输出:

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

我希望输出是:

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

有谁知道如何解决这个问题?谢谢

【问题讨论】:

  • 您的 JSON 结构毫无意义。请不要说必须用这个不能改。
  • 如果我的回答有帮助,请标记为已接受。

标签: python json sorting


【解决方案1】:

当您使用上下文管理器 (with ...) 时,您无需调用 .close()。上下文管理器会为您调用.close(),这就是重点。

您的 JSON 结构在很多方面都没有帮助。如果您无法更改它,则此方法有效(我不会解释原因,如果您无法弄清楚它,则表​​明您的数据结构存在严重错误,因为这些东西不应该是 很难。)

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)

有了更合理的输入数据结构,事情一下子变得简单了。

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

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

【讨论】:

  • 谢谢,你的数据结构好多了
  • @krystof18 它的主要缺点是您无法按名称索引玩家,即您无法使用that_player = data['players']['test1']。但是这个缺点非常容易克服:that_player = next(p for p in data['players'] if p['name'] == 'test1').
  • @krystof18 或者,构建临时查找字典也很容易by_name = {p['name']: p for p in data['players']}
猜你喜欢
  • 2016-03-12
  • 2020-11-21
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
相关资源
最近更新 更多