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

时间:2015-02-13 01:53:26

标签: python json sorting

我有一个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" }]

我想首先对id进行排序,我使用

sorted_list = sorted(json_list, key=lambda k: int(k['id']), reverse = False)

这只会按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" }]

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

1 个答案:

答案 0 :(得分:2)

使用元组添加第二个排序键-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'}]

因此,我们主要从{最低 - 最高的id排序,但我们使用score从最低 - 最低点打破关系。 dicts也是无序的,所以当你打印时没有使用OrderedDict就无法在得分之前输入id。

或者使用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'}]