在当前数据"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/