2013-12-17 21 views
-1

我想通過文本文件添加到字典中。基本上我的文本文件是這樣的:如何通過文本文件添加到字典

year3test 0 
year4test 0 
year5test 0 
year6test 0 

我想這些添加標題爲totals = {}與year3test空白字典,year4test是與0爲總計,讓我的字典裏是這樣的按鍵:

totals = { 
"year3test" : 0 
"year4test" : 0 
"year5test" : 0 
"year6test" : 0 
} 

我應該怎麼做?道歉,我對Python非常陌生。

+7

歡迎來到Stack Overflow!看起來你希望我們爲你寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。證明這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出和實際獲得的輸出(控制檯輸出,堆棧跟蹤,編譯器錯誤 - 無論是適用)。您提供的細節越多,您可能會收到的答案就越多。 –

+0

python docs是一個goog的地方,然後開始... http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files – corn3lius

回答

4
dict(line.split() for line in open('path/to/input')) 

或者,更詳細的方式:

with open('path/to/input') as infile: 
    answer = {} 
    for line in infile: 
     k,v = line.split() 
     answer[k] = v 
+0

在詳細的方式,當我使用它,我得到一個錯誤說「k,v = line.split TypeError:'builtin_function_or_method'對象是不可迭代的」 – user3112327

+0

哇哇哈哈,謝謝,多麼愚蠢的錯誤,歡呼! – user3112327

0

EVAL?

#!/usr/bin/python 

a = {'hello':1,'what':2,'which':3} #a is dict 

with open ("file1.txt","w") as f: 
    f.write ('%s' % a) # creating file. you may type it to see how it made (text) 

b = '' 
with open ("file1.txt","r") as f: 
    b = eval(f.read()) # reading dict file and converting it to dict. 

print type(b) # b is dict. 
+0

**輸入**不表示爲python對象,僅表示預期的輸出。 –

相關問題