Swordfish
Swordfish

Reputation: 31

Traversing through nested dictionary tree

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

Upvotes: 2

Views: 1421

Answers (1)

match
match

Reputation: 11060

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)

Upvotes: 1

Related Questions