10

我正在使用 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

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

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)

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

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)
4

2 回答 2

15

使用setdefault

如果键在字典中,则返回其值。如果不是,则插入值为默认值的键并返回默认值。

format_to_year_to_value_dict.setdefault(format_str, {})[year] = value

 

或者collections.defaultdict

format_to_year_to_value_dict = defaultdict(dict)
...
format_to_year_to_value_dict[format_str][year] = value

使用内部字典中的列表:

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)

或者

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)

对于未知深度的字典,你可以使用这个小技巧:

tree = lambda: defaultdict(tree)

my_tree = tree()
my_tree['a']['b']['c']['d']['e'] = 'whatever'
于 2013-04-04T18:56:53.093 回答
3
from collections import defaultdict
format_to_year_to_value_dict = defaultdict(dict)

这将创建一个字典,dict()当您访问不存在的键时调用该字典。

于 2013-04-04T18:57:14.283 回答