你已经接近了,但你有一些错误和一些遗漏的东西......
out_d = {} # init an empty dict
fr = open('products.txt','r')
for line in fr.readlines():
code, price, name = line.split(', ') # not code, name, price
print(line)
out_d[code] = [float(price), name] # adds a new dict entry
fr.close() # gets dedented
print(out_d)
一些事情...
(1) 根据您的输入文件,您要在', ' 上拆分,而不仅仅是','
(2) 看起来您的输入文件的顺序是代码/价格/名称而不是代码/名称/价格
(3) 您需要将价格从字符串转换为浮动
(4) 你的fr.close() 缩进太远了。它需要去齿。
此外,当您刚开始时,可以使用 open() 和 close()。但是有一个更好的方法,称为上下文管理器,它会自动为您执行close()。基本上,它看起来像这样:
out_d = {} # init an empty dict
with open('products.txt','r') as fr: # this creates a context
for line in fr.readlines():
code, price, name = line.split(', ') # not code, name, price
print(line)
out_d[code] = [float(price), name]
# fr.close() -- this line now goes away
print(out_d)
上面,fr.close() 行消失了,因为with 块完成时with open 调用close。