title: Turning a flat Python tuple into a nested dictionary?
body: <p>I have a tuple that looks like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>(
      ('Category 1', 40),
      ('Category 1 | Sub-Category 1', 20),
      ('Category 1 | Sub-Category 2', 20),
      ('Category 1 | Sub-Category 2 | Sub-Sub-Category 1', 5),
      ('Category 1 | Sub-Category 2 | Sub-Sub-Category 2', 15),
      ('Category 2', 20),
      ('Category 2 | Sub-Category 1', 15),
      ('Category 2 | Sub-Category 2', 5)
  )
  </code></pre>
  
  <p>I would like to turn it into a dictionary that looks like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>{
      'Category 1': {
          'count': 40,
          'children': {
              'Sub-Category 1': {'count': 20, 'children': []},
              'Sub-Category 2': {
                  'count': 20,
                  'children': {
                      'Sub-Sub-Category 1': {'count': 5, 'children': []},
                      'Sub-Sub-Category 2': {'count': 15, 'children': []}
                  }
              }
          }
      },
      'Category 2': {
          'count': 20,
          'children': {
              'Sub-Category 1': {'count': 15, 'children': []},
              'Sub-Category 2': {'count': 5, 'children': []},
          }
      }
  }
  </code></pre>
  
  <p>There are an arbitrary number of sub-categories. I'm having a tough time thinking of a Pythonic way of doing this. Any suggestions?</p>
  
  <p><strong>EDIT</strong>: In case anyone else runs into this kind of problem and wants a solution, here's what I (finally) came up with. I would post as an answer, but can't, due to the question being closed (sigh).</p>
  
  <pre class="lang-py prettyprint-override"><code>from itertools import groupby
  
  def categoriesdict(value, depth=0):
      categories = {}
      for name, children in groupby(value, lambda c: c[0].split(' | ')[depth]):
          # assumes that the first child is the group info
          categories[name] = {
              'count': children.next()[1],
              'children': categoriesdict(children, depth + 1)
          }
      return categories
  </code></pre>