解析文件并在字典中添加值,Python 3.5

时间:2015-11-13 17:49:16

标签: python dictionary

我想从文件中读取每个字符的分数,并将其作为键和值添加到字典中,在python 3.5中

这是代码

def read_score_file(score_dic):
    #open file
    f = open ('AA_score_file.txt', 'r')
    for line in f:
            #split current line 
            #1st part is Key = char
            #2nd part is value = score 
            score_dic.append(line.split())

    f.close()
    print (score_dic)

,而文本文件包含

A 1
B 2
C 3

2 个答案:

答案 0 :(得分:0)

line.split()返回一个数组,您可以将其分配给键值。

(key, value) = line.split()
score_dic[key] = value

答案 1 :(得分:0)

从头开始创建字典:

with open('AA_score_file.txt') as f: 
    score_dic = dict(map(str.split, f))
print(score_dic)

或者,要更新现有字典:

with open('AA_score_file.txt') as f: 
    score_dic.update(dict(map(str.split, f)))
print(score_dic)