2017-03-02 14 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 
関連する問題