2017-03-02 135 views
1

我創建了一個簡單的故障排除程序,我想將關鍵字和解決方案存儲在文本文件的列表中,然後我想提取這些數據並將其放入字典中,以便我可以將其用於代碼的其餘部分(檢查關鍵字)。Python 3.4.2:將文本文件中的數據轉換爲字典中的字典

的文本文件將是這個樣子:

iphone,put your phone in rice, wet, water, puddle 
iphone,replace your screen, cracked, screen, smashed 
iphone,turn off your phone,heat,heated,hot,fire 
samsung,put your phone in rice, wet, water, puddle 
samsung,replace your screen, cracked, screen, smashed 
samsung,turn off your phone,heat,heated,hot,fire 

行的第一部分是手機的型號和接下來就是解決方案和相應的項目是該解決方案的關鍵詞。

我想字典中是這個樣子:

dictionary = {"iphone":{"put your phone in rice":["wet","water","puddle"], 
         "replace your screen":["cracked","screen","smashed"], 
         "turn off your phone":["heat","heated","hot","fire"] 
         } 
       "samsung":{"put your phone in rice":["wet","water","puddle"], 
         "replace your screen":["cracked","screen","smashed"], 
         "turn off your phone":["heat","heated","hot","fire"] 
         } 
       } 

在實際事物的解決辦法是爲每個設備不同。

我一直在尋找了一會兒,知道解決我的解決方案將是這個樣子:

for i in data: 
    dictionary[i[0]] = data[i[0:]] 

,其中數據導入的文本文件。這段代碼絕對不起作用,但我知道一個可能的解決方案就是這樣的。

提前致謝!

回答

0

你接近:

dictionary = {} 
with open("file.txt") as f: 
    for line in f: 
     phone, key, *rest = line.strip().split(",") 
     if phone not in dictionary: 
      dictionary[phone] = {} 
     dictionary[phone][key] = rest 

而不是做phone, key, *rest = ...的,你確實可以做你嘗試過什麼:

data = line.strip().split(",") 
dictionary[data[0]][data[1]] = data[2:] 

但我認爲元組封裝更容易,更好看。

爲了使它不那麼煩人,你可以使用一個defaultdict

from collections import defaultdict 
dictionary = defaultdict(dict) 
with open("file.txt") as f: 
    for line in f: 
     phone, key, *rest = line.strip().split(",") 
     dictionary[phone][key] = rest