title: how to reassembled hierarchical data from a flat relation table?
body: <p>I'm trying to figure out how to translate a table that represents hierarchical data back into code. </p>
  
  <p>The table is configured as such: </p>
  
  <pre><code>| id | parent_id | name | 
  |----|-----------|------|
  | 1  |   null    | foo  |
  | 2  |    1      | bar  |
  | 3  |    1      | baz  | 
  | 4  |    3      | bif  | 
  | 5  |    1      | zip  | 
  
  etc...  
  </code></pre>
  
  <p>Such that, when reconstructed, it looks like this: </p>
  
  <pre><code>foo
   |-bar
   |-baz
      |-bif
   |-zip
  </code></pre>
  
  <p>I'm struggling to find a non-terrible way to build this list up in memory. </p>
  
  <p>Basically, the solution I've come to is just brute forcing my way through. e.g. (in pseudo Python)</p>
  
  <pre><code>output = {}
  for item in table:
     parent = get_parent(item) 
     if parent: 
         if parent not in output:  
             output[parent] = []
         output[parent_item].append(item) 
  </code></pre>
  
  <p>However, that only gets me half way. It correctly sticks the children under their immediate parent, but only <em>one</em> level up. This data is about 3 levels deep, so I guess I'd have to keep iterating over it until I couldn't find any more objects with parents. </p>
  
  <p>Suffice to say, my solution is bad, brittle, and I don't know what else to do.. What is the correct way to solve this problem? </p>