在 Python 中对嵌套词典列表进行排序

sort list of nested dictionaries in python

提问人:Vinutha Varun 提问时间:12/31/2022 最后编辑:James ZVinutha Varun 更新时间:1/1/2023 访问量:47

问:

如何对嵌套词典列表进行排序?字典的实际列表是

[
   {
      "Name":"21_12",
      "Details":[
         {
            "name":"Cat",
            "Data":[
               {
                  "status":"Passed",
                  "id":3,
                  "loop_count":1
               },
               {
                  "status":"Passed",
                  "id":5,
                  "loop_count":1
               }
            ]
         },
         {
            "name":"Dog",
            "Data":[
               {
                  "status":"Passed",
                  "id":1,
                  "loop_count":1
               },
               {
                  "status":"Passed",
                  "id":2,
                  "loop_count":1
               }
            ]
         }
      ]
   }
]

其中,即使在“数据”和“详细信息”中,字典的内部列表也应使用“id”进行排序

所需的输出:

[
   {
      "Name":"21_12",
      "Details":[
         {
            "name":"Dog",
            "Data":[
               {
                  "status":"Passed",
                  "id":1,
                  "loop_count":1
               },
               {
                  "status":"Passed",
                  "id":2,
                  "loop_count":1
               }
            ]
         },
         {
            "name":"Cat",
            "Data":[
               {
                  "status":"Passed",
                  "id":3,
                  "loop_count":1
               },
               {
                  "status":"Passed",
                  "id":5,
                  "loop_count":1
               }
            ]
         }
      ]
   }
]

尝试排序内置函数。没有按预期工作

python-3.x 字典 排序 嵌套列表

评论

0赞 starball 12/31/2022
请将 JSON 数据格式化为代码块。您可以查看 /editing-help 了解如何执行此操作。

答:

0赞 Domiziano Scarcelli 12/31/2022 #1

这应该可以完成以下工作:

def order_structure(structure):
    for details in structure:
        sorted_detail = sorted(details["Details"], key=lambda x: max(x["Data"], key= lambda y: y["id"])["id"])
        details["Details"] = sorted_detail
        for data in details["Details"]:
            sorted_data = sorted(data["Data"], key= lambda x: x["id"])
            data["Data"] = sorted_data
    

order_structure(structure)

如果您不想就地订购它,但想生成订购的副本,只需在structure.copy()

def get_ordered_structure(structure):
    structure_copy = structure.copy()
    for details in structure_copy:
        sorted_detail = sorted(details["Details"], key=lambda x: max(x["Data"], key= lambda y: y["id"])["id"])
        details["Details"] = sorted_detail
        for data in details["Details"]:
            sorted_data = sorted(data["Data"], key= lambda x: x["id"])
            data["Data"] = sorted_data
    return structure_copy

ordered_structure = get_ordered_structure(structure)

这样,原始结构就不会改变

即使主列表中有多个元素,如果它们遵循相同的结构,该函数也会起作用。

0赞 Sagar Madutha 12/31/2022 #2

你可以用python pandas来解决这个问题。

myDictionary = [
   {
      "Name":"21_12",
      "Details":[
         {
            "name":"Cat",
            "Data":[
               {
                  "status":"Passed",
                  "id":3,
                  "loop_count":1
               },
               {
                  "status":"Passed",
                  "id":5,
                  "loop_count":1
               }
            ]
         },
         {
            "name":"Dog",
            "Data":[
               {
                  "status":"Passed",
                  "id":1,
                  "loop_count":1
               },
               {
                  "status":"Passed",
                  "id":2,
                  "loop_count":1
               }
            ]
         }
      ]
   }
]

import pandas as pd
for i in range(len(myDictionary[0]["Details"])):
    df = pd.DataFrame(myDictionary[0]["Details"][i]["Data"])
    df.sort_values("id", inplace=True)
    myDictionary[0]["Details"][i]["Data"] = df.to_dict(orient="records")
    print(myDictionary)
0赞 tomerar 1/1/2023 #3

您可以将 Python 排序函数与正确的键函数一起使用

sorted_list = sorted(list_of_dicts, key=lambda x: x['Details']['Data']['id'])