title: How to initialize nested dictionaries in Python
body: <p>I'm using Python v2.7 dictionaries, nested one inside another like this:</p>
  
  <pre><code>def example(format_str, year, value):
    format_to_year_to_value_dict = {}
    # In the actual code there are many format_str and year values,
    # not just the one inserted here.
    if not format_str in format_to_year_to_value_dict:
      format_to_year_to_value_dict[format_str] = {}
    format_to_year_to_value_dict[format_str][year] = value
  </code></pre>
  
  <p>It seems a bit clumsy to initialize the first level dictionary with an empty dictionary before inserted into the second level dictionary.  Is there a way to set a value while at the same time creating a dictionary at the first level if there is not one already there?  I imagine something like this to avoid the conditional initializer:</p>
  
  <pre><code>def example(format_str, year, value):
    format_to_year_to_value_dict = {}
    add_dict_value(format_to_year_to_value_dict[format_str], year, value)
  </code></pre>
  
  <p>Also, what if the inner dict should itself initialize to a list?</p>
  
  <pre><code>def example(format_str, year, value):
    format_to_year_to_value_dict = {}
    # In the actual code there are many format_str and year values,
    # not just the one inserted here.
    if not format_str in format_to_year_to_value_dict:
      format_to_year_to_value_dict[format_str] = {}
    if not year in format_to_year_to_value_dict[format_str]:
      format_to_year_to_value_dict[format_str][year] = []
    format_to_year_to_value_dict[format_str][year].append(value)
  </code></pre>