简体   繁体   中英

Change structure of python dictionary using recursion

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM