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