1

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

1
  • Pardon the second dictionary as I couldn't post a question with most of the content as code Commented Aug 25, 2022 at 14:28

1 Answer 1

1

Recursion should work:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.