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