Wie zu initialisieren verschachtelten dictionaries in Python

Ich bin mit Python v2.7 Wörterbücher, geschachtelte eine innerhalb einer anderen, wie diese:

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

Scheint es ein bisschen ungeschickt, die zum initialisieren der ersten Ebene Wörterbuch mit einem leeren Wörterbuch, bevor Sie eingefügt in die zweite Ebene Wörterbuch. Gibt es eine Möglichkeit, um einen Wert festzulegen, während gleichzeitig die Erstellung eines Lexikons in der ersten Stufe, wenn es nicht schon da? Ich kann mir vorstellen so etwas zu vermeiden, die bedingte Initialisierung:

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)

Auch, was passiert, wenn die innere dict soll sich initialisieren, um eine Liste?

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)
InformationsquelleAutor WilliamKF | 2013-04-04
Schreibe einen Kommentar