title: How to flatten a nested dictionary without recursion?
body: <p>I came across this function that can flatten a dictionary:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>to test it I created a dictionnay that is nested <code>n</code> times like so:</p>
  
  <pre><code>nesteddict = {}
  for i in range(n, 0, -1):
      emptydict = {}
      emptydict[i] = nesteddict
      nesteddict = emptydict
  </code></pre>
  
  <p>the function works while <code>n</code> is less than 999, otherwise it hit recursion limit:</p>
  
  <pre><code>RecursionError: maximum recursion depth exceeded while calling a Python object
  </code></pre>
  
  <p>so after a little bit of searching it seems that <a href="https://stackoverflow.com/questions/931762/can-every-recursion-be-converted-into-iteration">any recursive function can rewritten to iteration</a> but I cant see how it could be done for the function I have to produce the same results.</p>
  
  <p>Another weird problem I came across while playing with this is if I try the code below for <code>n &gt;= 998</code>:</p>
  
  <pre><code>nesteddict = {}
  for i in range(n, 0, -1):
      emptydict = {}
      emptydict[i] = nesteddict
      nesteddict = emptydict
  print(nesteddict)
  </code></pre>
  
  <p>I get recursion error:</p>
  
  <pre><code>RecursionError: maximum recursion depth exceeded while getting the repr of an object
  </code></pre>
  
  <p>which is weird since I dont see any recursion here.</p>