如何在Python中初始化嵌套字典

Wil*_*mKF 9 python dictionary nested initialization python-2.7

我正在使用Python v2.7字典,在另一个内部嵌套,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

在插入第二级字典之前用空字典初始化第一级字典似乎有点笨拙.有没有办法设置一个值,同时在第一级创建字典,如果还没有一个字典?我想像这样的东西,以避免条件初始化器:

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)
Run Code Online (Sandbox Code Playgroud)

另外,如果内部字典本身应该初始化为列表怎么办?

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)
Run Code Online (Sandbox Code Playgroud)

Pav*_*sov 12

用途setdefault:

如果key在字典中,则返回其值.如果不是,请插入值为default的值并返回default.

format_to_year_to_value_dict.setdefault(format_str, {})[year] = value
Run Code Online (Sandbox Code Playgroud)

 

或者collections.defaultdict:

format_to_year_to_value_dict = defaultdict(dict)
...
format_to_year_to_value_dict[format_str][year] = value
Run Code Online (Sandbox Code Playgroud)

使用内部字典中的列表:

def example(format_str, year, value):
  format_to_year_to_value_dict = {}

  format_to_year_to_value_dict.setdefault(format_str, {}).setdefault(year, []).append(value)
Run Code Online (Sandbox Code Playgroud)

要么

def example(format_str, year, value):
  format_to_year_to_value_dict = defaultdict(lambda: defaultdict(list))

  format_to_year_to_value_dict[format_str][year].append(value)
Run Code Online (Sandbox Code Playgroud)

对于未知深度的dicts,您可以使用这个小技巧:

tree = lambda: defaultdict(tree)

my_tree = tree()
my_tree['a']['b']['c']['d']['e'] = 'whatever'
Run Code Online (Sandbox Code Playgroud)