如何在不使用多个循环的情况下从字典列表中获取每个记录的单独字典?

May*_*iya 4 arrays json dictionary list python-3.x

在当前数据"children"键将被修复。如果有任何可用的子数据,那么它必须在字典格式列表中

如果没有任何可用的子"children"项,则字典中没有可用的键。

我不想使用循环来分叉这些数据。 我想要相同的一致序列数据。请注意,将有任意数量的层次结构可用。

我希望所有这些数据都在字典格式列表中,例如给定的需求数据示例。

当前数据。

{
    "id": 2,
    "parent_id": 1,
    "name": "0",
    "is_active": true,
    "position": 1,
    "level": 1,
    "children": [
        {
            "id": 8,
            "parent_id": 1,
            "name": "01",
            "is_active": false,
            "position": 1,
            "level": 2,
            "children": [
                "id": 9,
                "parent_id": 1,
                "name": "010",
                "is_active": false,
                "position": 1,
                "level": 2,
                "children": [
                    <'Here N number of hirerchy availabe'>
                ]
            ]
        },

    ],
    "id": 3,
    "parent_id": 1,
    "name": "1",
    "is_active": true,
    "position": 1,
    "level": 1,
    "children": [
        {
            "id": 5,
            "parent_id": 1,
            "name": "03",
            "is_active": false,
            "position": 1,
            "level": 2,
            "children": [
                "id": 6,
                "parent_id": 1,
                "name": "030",
                "is_active": false,
                "position": 1,
                "level": 2,
                "children": [
                    <'Here N number of hirerchy availabe'>
                ]
            ]
        },

    ]
}
Run Code Online (Sandbox Code Playgroud)

要求。

[{
    "id": 2,
    "parent_id": 1,
    "name": "0",
    "is_active": true,
    "position": 1,
    "level": 1,
},
{
    "id": 3,
    "parent_id": 1,
    "name": "01",
    "is_active": false,
    "position": 1,
    "level": 2,
},
{
    "id": 3,
    "parent_id": 1,
    "name": "01",
    "is_active": false,
    "position": 1,
    "level": 2,
},{
    <N Number of dictionary data with consistant sequence>
}]
Run Code Online (Sandbox Code Playgroud)

合适的答案肯定会被接受。

blh*_*ing 5

您可以使用如下递归函数展平给定的嵌套数据结构:

def flatten(data):
    if isinstance(data, dict):
        return [data, *flatten(data.pop('children', ()))]
    return [subrecord for record in data for subrecord in flatten(record)]
Run Code Online (Sandbox Code Playgroud)

演示:https : //repl.it/@blhsing/BlankHatefulResources