2015-09-26 57 views
0

我需要一組嵌套字典{a:{} {b:{},{c:{}}}},其中a,b和c是鍵。我已經嘗試了下面的代碼。要將多個字典作爲值插入到單個鍵中

from collections import defaultdict 
def dictizeString(string,dictionary) : 
    while string.startswith('/'): 
     string = string[1:] 
    parts = string.split('/',1) 

    if len(parts)>1: 
     branch = dictionary.setdefault(parts[0],[dict()]) 
     dictionary[parts[0]].append(dict()) 
     dictizeString(parts[1], branch) 
    else: 
     if dictionary.has_key(parts[0]): 
      dictionary[parts[0]]=dict() 
     else: 
      dictionary[parts[0]]=[dict()] 
      dictionary[parts[0]].append(dict())    


d={} 

dictizeString('/a/b/c/d', d) 
print d 

執行此代碼會導致錯誤「列表」對象沒有屬性「setdefault」。該代碼適用於第一次迭代(即對於a),但是會爲第二次迭代(即b)拋出上述錯誤。

附加功能適用於代碼的最後6行中的else部分。我試圖在if情況下使用相同的邏輯,但它引發錯誤。

+0

你怎麼想的輸出看時打印Ð怎麼樣? – dopstar

+0

@dopstar我希望它能像這樣{a:{} {b:{},{c:{}}}}在打印d上。約書亞在我的代碼中的小改變是我所需要的。 – TheFallenOne

回答

0

嘗試:

from collections import defaultdict 
def dictizeString(string,dictionary) : 
    while string.startswith('/'): 
     string = string[1:] 
    parts = string.split('/',1) 

    if len(parts)>1: 
     branch = dictionary.setdefault(parts[0],[dict()]) 
     dictionary[parts[0]].append(dict()) 
     dictizeString(parts[1], branch[1]) # <--- branch -> branch[1] 
    else: 
     if dictionary.has_key(parts[0]): 
      dictionary[parts[0]]=dict() 
     else: 
      dictionary[parts[0]]=[dict()] 
      dictionary[parts[0]].append(dict())    


d={} 

dictizeString('/a/b/c/d', d) 
print d 

你第7行是什麼聲明設置默認是一個列表字典,但你儘量堅持到功能,其中它期待的字典。

+0

完美!正是我想要的。我花了一些時間才意識到.setdefault的返回值是一個關鍵值對。 – TheFallenOne

+0

很高興幫助,但我原來錯了,它不會返回對。你只是創建一個列表作爲價值並附加到它。 –

+0

有沒有一種有效的方法來使用這個嵌套字典中的鍵來訪問這些值呢?或者是通過打破ex的目錄結構來進行遞歸。 a/b/c/d as dict [a] [b] [c] [d]要走的路? – TheFallenOne

0

我知道你已經找到了答案,但你也可以這樣做:

def dictizeString(path, dictionary): 
    keys = path.lstrip('/').split('/') 
    current_key = None 
    for key in keys: 
     if current_key is None: 
      current_key = dictionary.setdefault(key, {}) 
     else: 
      current_key = current_key.setdefault(key, {}) 

d = {} 
dictizeString('/a/b/c/d', d) 
print d 

輸出變爲:{'a': {'b': {'c': {'d': {}}}}}

相關問題