-2

I have a dict of dicts that represents a tree:

{1: {2: 3, 4: 5}, 6: {7: 8, 9: 10}}

How can I turn it into all possible paths from the root to its leaves?

The otput should be smt like this:

[[1,2,3],[1,4,5],[6,7,8],[6,9,10]]

Is there some kind of Python dict comprehension moneliner that can solve this problem for any dict depth?

lotrus28
  • 848
  • 2
  • 10
  • 19

1 Answers1

6

This is what recursion is perfect for:

def paths(tree):
    if not isinstance(tree, dict):
        return [[tree]]
    return [[key] + path
            for key, value in tree.items()
            for path in paths(value)]

print(paths({1: {2: 3, 4: 5}, 6: {7: 8, 9: {10: 11, 12: 13}}}))

Output:

[[1, 2, 3], [1, 4, 5], [6, 9, 10, 11], [6, 9, 12, 13], [6, 7, 8]]
Alex Hall
  • 34,833
  • 5
  • 57
  • 89