Python列表中的字典按照该字典下的键值进行排序

时间:2024-01-10 11:09:02

列表中的字典按照该字典下的键值进行排序

这算是排序中比较复杂的一种情况吧,多重嵌套,按照某种规则进行排序。
如下面这个json(注:这里这是该列表中的一个项):

[
{
"stat": {
"question_id": 1339,
"question__article__live": null,
"question__article__slug": null,
"question__title": "Team Scores in Football Tournament",
"question__title_slug": "team-scores-in-football-tournament",
"question__hide": false,
"total_acs": 348,
"total_submitted": 656,
"frontend_question_id": 1212,
"is_new_question": true
},
"status": null,
"difficulty": {
"level": 2
},
"paid_only": true,
"is_favor": false,
"frequency": 0,
"progress": 0
},
{
"stat": {
"question_id": 1337,
"question__article__live": null,
"question__article__slug": null,
"question__title": "Design Skiplist",
"question__title_slug": "design-skiplist",
"question__hide": false,
"total_acs": 748,
"total_submitted": 1261,
"frontend_question_id": 1206,
"is_new_question": false
},
"status": null,
"difficulty": {
"level": 3
},
"paid_only": false,
"is_favor": false,
"frequency": 0,
"progress": 0
}
]

list里面是字典,字典里面还是字典,加入按照frontend_question_id进行排序,提供两种方法:

# 方法1,注:原列表为list1,排序后list2
list2 = sorted(list1, key=lambda x : x['stat']['question_id']) # 方法2
list1.sort(key=lambda x: x["stat"]['question_id'])

参考: python中列表排序,字典排序,列表中的字典排序