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

标签 arrays json python-3.x list dictionary

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

如果没有可用的 child ,则没有 "children"键在字典中可用。

I don't want to use the loop to bifurcate this data. I want the same consistent sequence data. Please note there will any number of hierarchy available.



我想要所有这些数据在 字典格式列表就像给定的需求数据示例。

当前数据。
{
    "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'>
                ]
            ]
        },

    ]
}

要求。
[{
    "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>
}]

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

最佳答案

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

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

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

关于arrays - 如何在不使用多个循环的情况下从字典列表中获取每个记录的单独字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59223750/

相关文章:

c++ - 在二维数组的每一行中查找具有 1 个元素的所有可能组合

c - 通用动态数组未正确更新属性

php - 如何在 PHP 中获取关联数组中的前 n 个键?

javascript - 从 LocalStorage 访问项目(Angular 1.2)

json - 如何制作动态JSON

python - 使用 Pytorch 安装 Open3d-Ml(在 MacO 上)

java - 如何在Java中识别字符串数组中最长的字母单词? (任何不带符号或数字的子字符串)

android - json 对象的 Volley Post 方法

python - 当输出字符超出 'z' 时,凯撒密码失败

python - 在 python df 中为变量分配一个连续编号