2

Below is the tree as a dictionary:

tree = {'X1': {0: {'X2': {0: 0, 1: {'X3': {0: 1, 1: 0}}}}, 1: {'X3': {0: 1, 1: 0}}}} 

How do I traverse through this tree in python and print only the nodes? Eg X1, X2...

Nae
  • 14,209
  • 7
  • 52
  • 79
Swordfish
  • 31
  • 2
  • This might be of use: https://stackoverflow.com/questions/3860813/recursively-traverse-multidimensional-dictionary-dimension-unknown – cs95 Feb 08 '18 at 20:42
  • 2
    Possible duplicate of [recursively traverse multidimensional dictionary, dimension unknown](https://stackoverflow.com/questions/3860813/recursively-traverse-multidimensional-dictionary-dimension-unknown) – Mihayl Feb 08 '18 at 21:39

1 Answers1

1

You need to step through each level of the dict, printing out all matching keys, and then calling the same function (recursion) if the value is a nested dict:

tree = {'X1': {0: {'X2': {0: 0, 1: {'X3': {0: 1, 1: 0}}}}, 1: {'X3': {0: 1, 1: 0}}}}

def recurse(d):
  for x, v in d.items():
    if str(x).startswith('X'):
        print(x)
    if isinstance(v, dict):
      recurse(v)

recurse(tree)
match
  • 10,388
  • 3
  • 23
  • 41