Home > Blockchain >  sort list of nested dictionaries in python
sort list of nested dictionaries in python

Time:12-31

How to sort list of nested dictionaries? Actual list of dictionary is

[
   {
      "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
               }
            ]
         }
      ]
   }
]

where the inner list of dictionaries should be sorted with "id" even inside the "Data" and in the "Details"

the output required:

[
   {
      "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
               }
            ]
         }
      ]
   }
]

Tried sorted inbuilt function. Didnt work as expected

CodePudding user response:

This should do the work:

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)

If you don't want to order it in-place, but want to generate an ordered copy, just do the same thing on 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)

In this way, the original structure doesn't change

The function works even if there is more than one element in the main list, if they follow the same structure.

CodePudding user response:

You can use python pandas to solve this problem.

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)
  • Related