【问题标题】:Change structure of python dictionary using recursion使用递归更改python字典的结构
【发布时间】:2022-10-15 02:36:21
【问题描述】:

我有以下字典:

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

我必须将其更改为以下格式,父键作为标签,值作为子级:

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

我试图实现这种递归但没有工作

【问题讨论】:

  • 请原谅第二本词典,因为我无法将大部分内容作为代码发布问题

标签: python json recursion


【解决方案1】:

递归应该起作用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-12
    • 2020-07-14
    • 2014-10-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多