2012-11-30 85 views
1

我嘗試從文件創建一個多字典;創建多維字典

k = [] 
with open('directory file txt',r) as f: 
    for line in f: 
     k.append(line.strip().split('.')) 

如何創建這樣的多詞典:

dict=[key1][key2][key3][key4]='value' 

其中key1是第一線的第一個元素,key2第二等

+1

是一樣的深度的「多維字典」始終? –

+1

而'k = line.strip.split('。')'不能是你跑的代碼;) –

+0

謝謝你的回答。但是,這是有效的,爲什麼不呢? – user1841492

回答

6

反轉列表和巢結果:

result = {} 
with open('directory file txt',r) as f: 
    for line in f: 
     keys = line.strip().split('.') 
     value = keys[-1] 
     for key in reversed(keys[1:-1]): 
      value = {key: value} 
     result[keys[0]] = value 

這不處理keys duplicat一切都好;如果您有重複鍵你需要使用稍微更麻煩的設置(defaultdict()不會處理的情況更好,我不認爲):

result = {} 
with open('directory file txt',r) as f: 
    for line in f: 
     keys = line.strip().split('.') 
     current = result 
     for key in keys[:-2]: 
      current = current.setdefault(key, {}) 
     current[keys[-2]] = keys[-1] 
+0

非常感謝。 – user1841492