我使用Python V2.7字典,嵌套一個內部另一個是這樣的:如何初始化的嵌套字典在Python
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在內部字典情況列表什麼? – WilliamKF 2013-04-04 19:06:56
只是編輯它。你只需要一個返回'defaultdict(list)'的函數,而不僅僅是缺少鍵的{}'。 – 2013-04-04 19:07:53