2016-11-16 45 views
-3

即時通訊全新的Python,我試圖查找它,但我仍然不知道你是如何做到這一點。你怎麼輸入一個文本文件到Python中的字典?

現在我的文本文件看起來像這樣:

'a':bla bla bla 
'b':bla bla bla 
'c':bla bla bla 

我想這個文件讀一本字典,使得第1列是關鍵,第2列是價值,即:

d = {'a':bla bla bla, 'b':bla bla bla, 'c':bla bla bla} 
+2

歡迎來到SO。你的問題太模糊了。如果你需要幫助,你需要付出一些努力並提出更具體的問題。參見[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)。 – CAB

+0

對不起,我感到困惑 –

+0

歡迎來到Stack Overflow!請回顧[如何問](http://stackoverflow.com/questions/how-to-ask)並編輯你的問題[最小,完整和可驗證的例子](http://stackoverflow.com/help/ MCVE)。 – Artemis

回答

1

python3中的手動方法:

a_dict = {} # To store the values in 
with open('file.txt') as input_file: 
    for line in input_file: 
     entry = line.split(":") # split for key, value 
     # store into dict, need to strip ' from the key and \n from value 
     a_dict[entry[0].strip("' ")] = entry[1].strip() 

print(a_dict) # Show the results 
相關問題