Matthew Kaplan
Matthew Kaplan

Reputation: 119

Maximum recursion depth exceeded on simple loop

I am trying to create a pretty straight forward loop that sorts through about 900 nested dictionaries and returns all of the values in lists named after the keys. I am getting the following recursion error though:

    Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "<stdin>", line 4, in myprint
  File "<stdin>", line 4, in myprint
  File "<stdin>", line 4, in myprint
  [Previous line repeated 995 more times]
  File "<stdin>", line 2, in myprint
RecursionError: maximum recursion depth exceeded while calling a Python object

Here's the code I'm currently using:

import pandas as pd
df = pd.read_csv("/Users/--/--/--/--/--/.csv")
def myprint(d):
    for k, v in data.items():
            if isinstance(v, dict):
                myprint(v)
            else:
                print("{0} : {1}".format(k, v))
                setattr(sys.modules[__name__], k, [v])
            
            
for i in df['file_num']:
    with open("/Users/--/--/--/--/allDAFs{}.json".format(i)) as f:
        data=json.load(f)
    myprint(data)

I would greatly appreciate any potential insight into how this can be fixed or worked around. Thank you.

Upvotes: 0

Views: 207

Answers (2)

Adhun Thalekkara
Adhun Thalekkara

Reputation: 723

check if your program works for one recursion. then if u want to increase your recursion limit you can do this

sys.setrecursionlimit(2000)

Upvotes: 0

Jannes Carpentier
Jannes Carpentier

Reputation: 1898

The problem is this loop for k, v in data.items(): gets called every time you call the function.

I think you made the typo data.items instead of d.items

import pandas as pd
df = pd.read_csv("/Users/--/--/--/--/--/.csv")
import pandas as pd
df = pd.read_csv("/Users/--/--/--/--/--/.csv")
def myprint(d):
#   for k, v in data.items():
    for k, v in d.items():
            if isinstance(v, dict):
                myprint(v)
            else:
                print("{0} : {1}".format(k, v))
                setattr(sys.modules[__name__], k, [v])
            
            
for i in df['file_num']:
    with open("/Users/--/--/--/--/allDAFs{}.json".format(i)) as f:
        data=json.load(f)
    myprint(data)

Upvotes: 2

Related Questions