Gabriel
Gabriel

Reputation: 237

recursion print error nested dict() object in python

Let's make it a bit easier.
Code:

level3 = {'a':'aa'}                                                             
level2 = {'b':level3, 'd':level3}                                               
level1 = {'j':level2, 'k':level2}                                               

def print_rec(node = None):                                                 
    if node is None:                                                            
        node = level1                                                           
    if node == 'aa':                                                            
        return                                                                  
    for key, successor in node.items():                                         
        print(key,":",node.get(key))                                            
        print_rec(successor)                                                

print_rec()

Outputs:

k : {'d': {'a': 'aa'}, 'b': {'a': 'aa'}}
d : {'a': 'aa'}
a : aa
b : None
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    print_rec(level1)
  File "test.py", line 11, in print_rec
    print_rec(node)
  File "test.py", line 11, in print_rec
    print_rec(node)
  File "test.py", line 8, in print_rec
    for key in node:
TypeError: 'NoneType' object is not iterable

I think node = node.get(key) will be executed only if the key is in node. So why the new node will get a NoneType? Anyone can help?

Upvotes: 0

Views: 230

Answers (1)

flornquake
flornquake

Reputation: 3366

In the for loop, it seems like you're using the name node for two different things:

for key in node:                                                            
    print(key,":",node.get(key))                                            
    node = node.get(key)                                                    
    print_rec(node)

When in the first iteration, you change the value of node. In the second iteration, when you do node.get(key), you're using the new node, but you want to be using the original node.

This should help:

for key in node:
    print(key,":",node.get(key))
    successor = node.get(key)
    print_rec(successor)

It can be written even more concisely like this:

for key, successor in node.items():
    print(key,":",successor)
    print_rec(successor)

Upvotes: 4

Related Questions