2013-04-04 63 views
7

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

回答

12

使用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' 
+0

有沒有像defaultdict在內部字典情況列表什麼? – WilliamKF 2013-04-04 19:06:56

+0

只是編輯它。你只需要一個返回'defaultdict(list)'的函數,而不僅僅是缺少鍵的{}'。 – 2013-04-04 19:07:53

3
from collections import defaultdict 
format_to_year_to_value_dict = defaultdict(dict) 

這將創建一個調用dict()一本字典,當你訪問鍵,唐」不存在。