title: How to build a recursive dictionary tree from an ordered adjacency list
body: <p>I've been trying to figure this out all day and Im at my wits end. Maybe I'm just getting to old for this.</p>
  
  <p>I'm trying to build a tree for the load_bulk feature on django-treebeard as specified <a href="https://tabo.pe/projects/django-treebeard/docs/tip/api.html#treebeard.models.Node.load_bulk" rel="nofollow">here</a></p>
  
  <p>To save you looking, it should look like this:</p>
  
  <pre><code>data = [{'data':{'desc':'1'}},
           {'data':{'desc':'2'}, 'children':[
            {'data':{'desc':'21'}},
            {'data':{'desc':'22'}},
            {'data':{'desc':'23'}, 'children':[
              {'data':{'desc':'231'}},
            ]},
            {'data':{'desc':'24'}},
          ]},
          {'data':{'desc':'3'}},
          {'data':{'desc':'4'}, 'children':[
            {'data':{'desc':'41'}},
          ]},
  ]
  </code></pre>
  
  <p>'data' holds the record, and if it has children, 'children' is a list of more 'data' dicts (that can also contain a list of children and so on recursively)</p>
  
  <p>I get the data as an ordered list (ordered as in depth first, not by id):</p>
  
  <p>e.g:</p>
  
  <pre><code>[
      {'id': 232, 'name': 'jon', 'parent': 'None'}
      {'id': 3522, 'name': 'dave', 'parent': '232'}
      {'id': 2277, 'name': 'alice', 'parent': '3522'}
      {'id': 119, 'name': 'gary', 'parent': '232'}
      {'id': 888, 'name': 'gunthe', 'parent': '119'}
      {'id': 750, 'name': 'beavis', 'parent': 'None'}
      {'id': 555, 'name': 'urte', 'parent': '750'}
  ]
  </code></pre>
  
  <p>How can I transform it into a treebeard compliant dictionary that would look like this (typo's excepted):</p>
  
  <pre><code>[
  {'data': {'id': 232, 'name': 'jon', 'parent': 'None'},
   'children': [
                {'data': {'id': 3522, 'name': 'dave', 'parent': '232'},
                 'children': [
                              {'data': {'id': 2277, 'name': 'alice', 'parent': '3522'}}
                             ]
                }
                {'data': {'id': 119, 'name': 'gary', 'parent': '232'},
                 'children': [
                              {'id': 888, 'name': 'gunthe', 'parent': '119'}
                             ]
                }
               ]
  {'data': {'id': 750, 'name': 'beavis', 'parent': 'None'},
   'children': [
                {'id': 555, 'name': 'urte', 'parent': '750'}
               ]
  }
  </code></pre>
  
  <p>]</p>
  
  <p>I guess I need some kind of recursion function seeing as its a recursive structure but all my attempts have failed. My brain doesnt do recursion so good.</p>
  
  <p>I did a lot of searching and found mostly solutions pertaining to lists or other structures that i cant mould to fit. I'm a relative noob. ps i had more fun manually typing out the example than i did the rest of day (apart from dinner time).</p>