如何通过文本文件添加到字典

时间:2013-12-17 19:47:17

标签: python file text dictionary

我想通过文本文件添加到字典中。基本上我的文本文件是这样的:

year3test 0
year4test 0
year5test 0
year6test 0

我想将这些添加到一个标题为totals = {}的空白字典中,其中包含year3test,year4test是以0为总计的键,因此我的字典看起来像这样:

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

我应该怎么做?道歉,我对python很新。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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.