Python按两个键值对JSON列表进行排序

jif*_*ent 2 python sorting json

我有一个 JSON 列表,如下所示:

[{ "id": "1", "score": "100" },
{ "id": "3", "score": "89" },
{ "id": "1", "score": "99" },
{ "id": "2", "score": "100" },
{ "id": "2", "score": "59" }, 
{ "id": "3", "score": "22" }]
Run Code Online (Sandbox Code Playgroud)

我想先对id进行排序,我用过

sorted_list = sorted(json_list, key=lambda k: int(k['id']), reverse = False)
Run Code Online (Sandbox Code Playgroud)

这只会按 id 对列表进行排序,但基于 id,我也想按意愿对分数进行排序,我想要的最终列表是这样的:

[{ "id": "1", "score": "100" },
{ "id": "1", "score": "99" },
{ "id": "2", "score": "100" },
{ "id": "2", "score": "59" },
{ "id": "3", "score": "89" }, 
{ "id": "3", "score": "22" }]
Run Code Online (Sandbox Code Playgroud)

因此,对于每个 id,也要对他们的分数进行排序。知道怎么做吗?

Pad*_*ham 5

使用元组添加第二个排序键-int(k["score"])在打破关系并删除时反转顺序reverse=True

sorted_list = sorted(json_list, key=lambda k: (int(k['id']),-int(k["score"])))

[{'score': '100', 'id': '1'}, 
 {'score': '99', 'id': '1'}, 
 {'score': '100', 'id': '2'}, 
 {'score': '59', 'id': '2'},
 {'score': '89', 'id': '3'}, 
 {'score': '22', 'id': '3'}]
Run Code Online (Sandbox Code Playgroud)

所以我们主要id从最低到最高排序,但我们使用score从最高到最低来打破平局。dicts 也是无序的,所以在打印时没有办法将 id 放在 score 之前,而不可能使用 OrderedDict。

或者使用 pprint:

from pprint import pprint as pp

pp(sorted_list)

[{'id': '1', 'score': '100'},
 {'id': '1', 'score': '99'},
 {'id': '2', 'score': '100'},
 {'id': '2', 'score': '59'},
 {'id': '3', 'score': '89'},
 {'id': '3', 'score': '22'}]
Run Code Online (Sandbox Code Playgroud)