我正在使用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)
另外,如果内部字典本身应该初始化为列表,该怎么办?
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)
defaultdict(list)
而不是{}
的函数来处理缺失的键。 - Pavel Anossov