如何将文件制作成字典? [英] How to make a file into a dictionary?
本文介绍了如何将文件制作成字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将文件放入具有多个值的字典中
I'm having trouble trying to get my file into a dictionary with multiple values
bench,103,222,32
table,833,99,23
chair,83,22,882
到目前为止,我的代码是
My code so far is
sol={}
infile= open("furniture.dat","r")
for line in infile:
key,value=line.split(",")
我试图将单词作为键并将数字作为字典的值,但在split()上收到错误
I'm trying to get the words as keys and the number as the value for the dictionary, but receiving error on the split()
推荐答案
my_dict = {}
with open('furniture.dat', 'r') as f:
for line in f.readlines():
line_list = line.split(',')
new_dict = dict(zip(line_list, [(line_list[1:])]))
my_dict.update(new_dict)
print(my_dict)
输出字典:{'bench': ['103', '222', '32'], 'table': ['833', '99', '23'], 'chair': ['83', '22', '882']}
这篇关于如何将文件制作成字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文