Python 3.4.2:将文本文件中的数据转换为字典中的字典

Python 3.4.2:将文本文件中的数据转换为字典中的字典

问题描述:

我创建了一个简单的故障排除程序,我想将关键字和解决方案存储在文本文件的列表中,然后我想提取这些数据并将其放入字典中,以便我可以将其用于代码的其余部分(检查关键字)。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:]] 

,其中数据导入的文本文件。这段代码绝对不起作用,但我知道一个可能的解决方案就是这样的。

提前致谢!

你接近:

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