windows-嵌套字典的树形显示

windows-like tree show for nested dict

问题应该很清楚了。我有一个嵌套的字典,我很想从中得到一个字符串,它看起来像文件夹的 windows 树命令。

这将是一个示例字典:

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

预期结果为:

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

对此的正确表述不是我的主要目标,只要每个 "more nested" 实体有更多的缩进就很棒了。我知道我需要创建一个递归函数,但我的尝试失败了,甚至不值得分享。所以我来了:)

我的代码尝试按要求...

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}

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

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

正在更新@Ajax1234 的回答,缺少一行。

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))
         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