gpt4 book ai didi

python - 将字典列表转换为嵌套字典列表

转载 作者:行者123 更新时间:2023-12-04 00:56:32 27 4
gpt4 key购买 nike

针对上述问题,我尝试并看到了多种解决方案,但找不到适合我的情况的解决方案。我有以下词典列表。

input_list = [
{'k0':'v0','level':0,'row':0},
{'k1':'v1','level':1,'row':1},
{'k2':'v2','level':2,'row':2},
{'k3':'v3','level':2,'row':3},
{'k4':'v4','level':1,'row':4},
{'k5':'v5','level':2,'row':5},
{'k6':'v6','level':1,'row':6},
{'k7':'v7','level':0,'row':7},
{'k8':'v8','level':1,'row':8},
{'k9':'v9','level':2,'row':9},
]

我需要通过以下方式将此列表转换为嵌套字典列表

[
{'k0':'v0',
'level':0,
'child':[
{'k1':'v1','level':1,'child':[{'k2':'v2','level':2},
{'k3':'v3','level':2}]},
{'k4':'v4','level':1,'child':[{'k5':'v5','level':2}]},
{'k6':'v6','level':1}
]},

{'k7':'v7',
'level':0,
'child':[{'k8':'v8','level':1,'child':[{'k9':'v9','level':2}]}]}
]

我尝试过的解决方案如下

levels = dict()
for n in input_list:
levels.setdefault(n['level'], []).append(n)

这给了我分级分离的字典,但我无法越过这段代码来获得我想要的解决方案

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

您可以通过 itertools.groupby 使用递归:

from itertools import groupby as gb
data = [{'k0': 'v0', 'level': 0, 'row': 0}, {'k1': 'v1', 'level': 1, 'row': 1}, {'k2': 'v2', 'level': 2, 'row': 2}, {'k3': 'v3', 'level': 2, 'row': 3}, {'k4': 'v4', 'level': 1, 'row': 4}, {'k5': 'v5', 'level': 2, 'row': 5}, {'k6': 'v6', 'level': 1, 'row': 6}, {'k7': 'v7', 'level': 0, 'row': 7}, {'k8': 'v8', 'level': 1, 'row': 8}, {'k9': 'v9', 'level': 2, 'row': 9}]
_d = [{a:b for a, b in i.items() if a not in {'row'}} for i in data]

def get_results(d, l = 0):
r, p = [(a, list(b)) for a, b in gb(d, key=lambda x:x['level'] == l)], []
for a, b in r:
if a:
p.extend(b)
else:
p[-1]['child'] = get_results(b, l+1)
return p

import json
print(json.dumps(get_results(_d), indent=4))

输出:

[
{
"k0": "v0",
"level": 0,
"child": [
{
"k1": "v1",
"level": 1,
"child": [
{
"k2": "v2",
"level": 2
},
{
"k3": "v3",
"level": 2
}
]
},
{
"k4": "v4",
"level": 1,
"child": [
{
"k5": "v5",
"level": 2
}
]
},
{
"k6": "v6",
"level": 1
}
]
},
{
"k7": "v7",
"level": 0,
"child": [
{
"k8": "v8",
"level": 1,
"child": [
{
"k9": "v9",
"level": 2
}
]
}
]
}
]

关于python - 将字典列表转换为嵌套字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62202547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com