Here it is my tree, a nested dictionary
tree = {"root": {"branch_a": {"branch_aa": 0, "branch_ab": 1},
"branch_b": 1,
"branch_c": {"branch_ca": {"branch_caa": 0}}}}
I managed to write a function that prints all the leaves
def print_leaves(tree):
if not hasattr(tree, "__iter__"):
print(tree)
elif isinstance(tree, dict):
for branch in tree.values():
print_leaves(branch)
which produces the desired output
0
1
1
0
At this point I thought it would have been nice to decouple the action (printing in this case) from the access to the leaves. So I modified the function above slightly, turned it into a generator and moved the printing part in a for loop.
def generate_leaves(tree):
if not hasattr(tree, "__iter__"):
yield tree
elif isinstance(tree, dict):
for branch in tree.values():
generate_leaves(branch)
for leaf in generate_leaves(tree):
print(leaf)
... which unfortunately doesn't work.
First of all why, doesn't it work? And then, of course, how to properly write a leaf generator?