gpt4 book ai didi

python - 从路径列表中生成字典

转载 作者:行者123 更新时间:2023-11-28 18:59:08 24 4
gpt4 key购买 nike

我有一个路径列表:

paths = [
"root/child1/file1",
"root/child1/file2",
"root/child2/file1"
]

我想用 python 将其解析为 dict(或 dictlist),如下所示:

{
"text": "root",
"children": [
{
"text": "child1",
"children": [
{
"text": "file1",
"children": []
},
{
"text": "file2",
"children": []
}
]
},
{
"text": "child2",
"children": [
{
"text": "file2",
"children": []
}
]
}

我尝试写一些递归函数,但没有成功。示例:

def path2dict(path, depth):
d = {}
text = path.split('/')[0]
d['text'] = text
depth = depth + 1
d['children'] = [path2dict(p, depth) for p in path.split('/')[depth:]]
return d

paths = [
"root/child1/file1",
"root/child1/file2",
"root/child2/file1"
]

depth = 0
for path in paths:
d = path2dict(path, depth)
print(d)

最佳答案

很抱歉没有使用您现有的解决方案,但我有一些其他的:

def stage1(paths):
result = {}
for path in paths:
split = path.split('/')
current = result
for part in split:
current.setdefault(part, {})
current = current[part]
return result


def stage2(dct):
return [
{
'text': key,
'children': stage2(value)
}
for key, value in dct.items()
]


after_stage1 = stage1(paths)

# after_stage1 is
# {
# 'root': {
# 'child1': {
# 'file1': {},
# 'file2': {}
# },
# 'child2': {
# 'file1': {}
# }
# }
# }

after_stage2 = stage2(after_stage1)

# after_stage2 contains exactly what you need

关于python - 从路径列表中生成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54805659/

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