我想从文件中读取每个字符的分数,并将其作为键和值添加到字典中,在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
答案 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)