title: Flattening a list of dicts of lists of dicts (etc) of unknown depth in Python (nightmarish JSON structure)
body: <p>I'm dealing with a JSON structure which is output to me in structures like this:</p>
  
  <pre><code>[{u'item': u'something',
    u'data': {
              u'other': u'',
              u'else':
                 [
                    {
                      u'more': u'even more',
                      u'argh':
                           {
                              ...etc..etc
  </code></pre>
  
  <p>As you can see, these are nested dicts and lists. 
  There is much discussion about flattening these recursively, but I haven't found one yet that can deal with a list of dictionaries which may in turn contain either dictionaries of lists, lists of lists, dictionaries of dictionaries etc; which are of unknown depth! In some cases the depth may be up to 100 or so. 
  I've been trying this so far without much luck (python 2.7.2):</p>
  
  <pre><code>def flatten(structure):
      out = []
      for item in structure:
          if isinstance(item, (list, tuple)):
              out.extend(flatten(item))
          if isinstance(item, (dict)):
              for dictkey in item.keys():
                  out.extend(flatten(item[dictkey]))
          else:
              out.append(item)
      return out
  </code></pre>
  
  <p>Any ideas? </p>
  
  <p><em><strong>UPDATE</em></strong>
  This pretty much works:</p>
  
  <pre><code>def flatten(l):
      out = []
      if isinstance(l, (list, tuple)):
          for item in l:
              out.extend(flatten(item))
      elif isinstance(l, (dict)):
          for dictkey in l.keys():
              out.extend(flatten(l[dictkey]))
      elif isinstance(l, (str, int, unicode)):
          out.append(l)
      return out
  </code></pre>