title: Placing list items correctly in a nested dictionary
body: <p>I have a list of text blocks like this:</p>
  <pre><code>blocks = [
      &quot;created may 27th&quot;, 
      &quot;Introduction Foo Bar Bar&quot;, 
      &quot;Lorem te Ipsum&quot;, 
      &quot;Method Participants Foo Foo Bar Procedure Baz&quot;
  ]
  </code></pre>
  <p>And the following dictionary:</p>
  <pre><code>structure = {
      &quot;text&quot;: [],
      &quot;Introduction&quot; : {
          &quot;text&quot;: []
      },
      &quot;Method&quot;: {
          &quot;Participants&quot; : {
              &quot;text&quot;: []
          },
          &quot;Procedure&quot;: {
              &quot;text&quot;: []
          }
      }
  }
  </code></pre>
  <p>I want to combine the two so that the text blocks end up in their correct location based on the order of presence and possible header strings at their start to create the following structure:</p>
  <pre><code>structure = {
      &quot;text&quot;: [&quot;created may 27th&quot;]
      &quot;Introduction&quot; : {
          &quot;text&quot;: [&quot;Foo Bar Bar&quot;, &quot;Lorem te Ipsum&quot;]
      }
      &quot;Method&quot;: {
          &quot;Participants&quot; {
              &quot;text&quot;: [&quot;Foo Foo Bar&quot;]
          },
          &quot;Procedure&quot;: {
              &quot;text&quot;: [&quot;Baz&quot;]
          }
  }
  </code></pre>
  <p>This should work for a list of any length, as well as for a dictionary with any depth.</p>
  <p>My intuition told me to loop through the text block and then to recursively find its location by checking if <code>block.startswith(header)</code>, if so splitting the header and repeating with the right partition of the text block, and otherwise appending to currently selected 'text' value. The biggest challenge for me is having 2 for-loops traversing through the text blocks and dictionary items, while keeping track of the location in the dictionary and being able to move towards the next item when it means going back up into the tree.</p>
  <p>This is what I have tried:</p>
  <pre class="lang-py prettyprint-override"><code>def add_block(block, current_section, header_index=0):
      header = list(current_section.keys())[header_index]
      if not block.strip().startswith(header):
          current_section['text'].append(block)
      elif block.startswith(header):
          block = block.partition(header)[-1]
          add_block(block, current_section[header], header_index+1)    
  
  for block in blocks:
      add_block(block, structure)
  </code></pre>