Home > Blockchain >  Change structure of python dictionary using recursion
Change structure of python dictionary using recursion

Time:08-26

I have the following dictionary:

{
    "Land": {
        "2018": {
            "VALUE:Avg": 49.0,
            "VALUE:Sum": 49.0
        },
        "2008": {
            "VALUE:Avg": 27.24,
            "VALUE:Sum": 27.24
        }
    },
    "Air": {
        "2010": {
            "VALUE:Avg": 57.4,
            "VALUE:Sum": 57.4
        },
        "2017": {
            "VALUE:Avg": 30.72,
            "VALUE:Sum": 61.44
        }
    }
}

I have to change it to following format with parent keys as labels and the values as children:

[
    {
        "label": "Land",
        "children": [
            {
                "label": "2018",
                "children": [
                    {
                        "label": "VALUE:Avg"
                    },
                    {
                        "label": "VALUE:Sum"
                    }
                ]
            },
            {
                "label": "2008",
                "children": [
                    {
                        "label": "VALUE:Avg"
                    },
                    {
                        "label": "VALUE:Sum"
                    }
                ]
            }
        ]
    },
]

I tried to achieve this recursion but not working

CodePudding user response:

Recursion should work, please help check whether the following piece of code do the job

def transfer(mydict):

    result = []

    for key, value in mydict.items():
        temp = {"label":key}
        if isinstance(value, dict):
            temp["children"] = transfer(value)
        result.append(temp)
    return result
  • Related