[Windows类似的树显示嵌套字典

问题描述 投票:0回答:1

问题应该很清楚。我有一个嵌套的字典,我很乐意从中取出一个字符串,看起来像是文件夹的Windows树命令。

这将是一个示例字典:

dictionary = {"a": {"b": {"c": None}, "d": None}, "e": None}

预期结果将是:

├───a
│   ├───b
│   │   └───c
│   └d
└──e

正确的表述不是我的主要目标,每个“更多嵌套”的实体只有更多的缩进将是惊人的。我知道我将需要创建一个递归函数,但是我的尝试被破坏了,以至于它甚至不值得共享。所以我来到这里:)

我按要求尝试输入代码...

dictio = {"a": {"b": {"c": None}, "d": None}, "e": None}


x = 0
end = {}
def recursive(dic):
    global x
    for key in dic:
        if isinstance(dic[key], dict):
            end[list(dic[key].keys())[0]] = x
            x += 1
            recursive(dic[key])
        else:
            end[list(dic.keys())[0]] = x
            x -= 1

recursive(dictio)
print(end)

这导致{'b':1,'c':2,'a':0}

python python-3.x dictionary recursion indentation
1个回答
0
投票

您可以对生成器使用递归:

dictionary = {"a": {"b": {"c": None}, "d": None}, "e": None}
def to_tree(d, c = 0):
  for a, b in d.items():
     yield '   '.join('|' for _ in range(c+1))+f'---{a}'
     yield from ([] if b is None else to_tree(b, c+1))

print('\n'.join(to_tree(dictionary)))

输出:

|---a
|   |---b
|   |   |---c
|   |---d
|---e
© www.soinside.com 2019 - 2024. All rights reserved.