Search code examples
pythonpython-3.xdictionaryrecursionindentation

windows-like tree show for nested dict


the problem should be pretty clear. I have a nested dict and I would love to get a string out of it which looks like the windows tree command for folders.

This would be an example dict:

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

And the expected result would be:

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

The correct represantation of this is not my primary goal, just have more indentions per "more nested" entity would be amazing. I know that I will need to create a recursive function, but my attempts are so broken that its not even worth sharing them. So I came here :)

My code attempt as requested...

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)

This results in {'b': 1, 'c': 2, 'a': 0}


Solution

  • You can use recursion with a generator:

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

    Output:

    |---a
    |   |---b
    |   |   |---c
    |   |---d
    |---e