I came across this function that can flatten a dictionary:
def flatten(dictionnary, container=None):
if container is None:
container = []
for k, v in dictionnary.items():
container.append(k)
if v:
flatten(v, container)
return container
to test it I created a dictionnay that is nested n
times like so:
nesteddict = {}
for i in range(n, 0, -1):
emptydict = {}
emptydict[i] = nesteddict
nesteddict = emptydict
the function works while n
is less than 999, otherwise it hit recursion limit:
RecursionError: maximum recursion depth exceeded while calling a Python object
so after a little bit of searching it seems that any recursive function can rewritten to iteration but I cant see how it could be done for the function I have to produce the same results.
Another weird problem I came across while playing with this is if I try the code below for n >= 998
:
nesteddict = {}
for i in range(n, 0, -1):
emptydict = {}
emptydict[i] = nesteddict
nesteddict = emptydict
print(nesteddict)
I get recursion error:
RecursionError: maximum recursion depth exceeded while getting the repr of an object
which is weird since I dont see any recursion here.