title: How do I build a tree dynamically in Python
body: <p>A beginner Python/programming question... I'd like to build a tree structure in Python, preferably based on dictionaries. I found code that does this neatly:</p>
  
  <pre><code>Tree = lambda: collections.defaultdict(Tree)
  root = Tree()
  </code></pre>
  
  <p>This can easily be populated like:</p>
  
  <pre><code> root['toplevel']['secondlevel']['thirdlevel'] = 1
   root['toplevel']['anotherLevel'] = 2
   ...etc.
  </code></pre>
  
  <p>I'd like to populate the levels/leaves dynamically so that I can add as many levels as needed, and where the leaves can be at any level. How do I do that?</p>
  
  <p>Any help is greatly appreciated.</p>