2016-11-30 197 views
2

創建一個嵌套的3D字典,我試圖讓3D辭典蟒蛇在Python 2.7

我有價值觀在我的名單,我想他們的方式相關聯的問題。

這裏是我的代碼:

def nestedDictionary3D(L1, L2): 
""" 
Requires: L1 and L2 are lists 
Modifies: Nothing 
Effects: Creates a 3D dictionary, D, with keys of each item of list L1. 
      The value for each key in D is a dictionary, which 
      has keys of each item of list L2 and corresponding 
      values of empty dictionaries. Returns the new dictionary D. 
""" 
    t1 = tuple(L1) 
    t2 = tuple(L2) 
    D = {t1: {t2: {}}} 
    return D 

這裏是預期的輸出和我的輸出:

測試用例輸入參數:

['dolphin', 'panda', 'koala'], ['habitat', 'diet', 'lifespan'] 

我的返回值:

{('dolphin', 'panda', 'koala'): {('habitat', 'diet', 'lifespan'): {}}} 

Expec泰德返回值:

{'dolphin': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 'panda': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 'koala': {'diet': {}, 'habitat': {}, 'lifespan': {}}} 

測試用例輸入參數:

['Ann Arbor', 'San Francisco', 'Boston'], ['restaurants', 'parks', 'hotels'] 

我的返回值:

{('Ann Arbor', 'San Francisco', 'Boston'): {('restaurants', 'parks', 'hotels'): {}}} 

預期的返回值:

{'San Francisco': {'hotels': {}, 'parks': {}, 'restaurants': {}}, 'Ann Arbor': {'hotels': {}, 'parks': {}, 'restaurants': {}}, 'Boston': {'hotels': {}, 'parks': {}, 'restaurants': {}}} 

有人能解釋一下我我做錯了嗎?

謝謝!

+0

老兄非常感謝! –

回答

2

爲了達到這個目的,你可以使用嵌套字典理解表達爲:

animal, property = ['dolphin', 'panda', 'koala'], ['habitat', 'diet', 'lifespan'] 

my_dict = {a: {p: {} for p in property} for a in animal} 

其中my_dict將持有的價值:

{'dolphin': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 
'panda': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 
'koala': {'diet': {}, 'habitat': {}, 'lifespan': {}}} 

因此,你的函數可以簡單地寫爲:

def nestedDictionary3D(L1, L2): 
    return {l1: {l2: {} for l2 in L2} for l1 in L1} 

您不需要輸入list中的值到tuple