2014-02-26 98 views

回答

4

您可以創建多層次的嵌套字典與collections.defaultdict,這樣

from collections import defaultdict 
def multi_level_dict(): 
    return defaultdict(multi_level_dict) 

你可以使用它像我測試了這個

my_dict = multi_level_dict() 
my_dict[1][2][3] = "cabbage" 
my_dict[1][4][5] = "salad" 
from pprint import pprint 
pprint(my_dict) 
# {1: {2: {3: 'cabbage'}, 
#  4: {5: 'salad'}}} 
+0

美麗,從來沒有見過這個,非常感謝! – smassey

+0

如此聰明的方式,TIL〜 – zhangxaochen

0
>>> a = {} 
>>> b = {} 
>>> a['key1'] = b 
>>> b['key2'] = 'final value' 
>>> a['key1'] 
{'key2': 'final value'} 
>>> a['key1']['key2'] 
'final value' 
>>> 

,它的作品!

+0

a ['1'] = {'2':{'3':3}}然後調用['1'] ['2'] ['3'] – WeizhongTu