我有这个文本文件:
English
hello bye
italian
ciao hola
spanish
hola chao
我想从每两行连续的行创建一个字典:
{
'English': 'hello bye',
'italian': 'ciao hola',
'spanish': 'hola chao',
}
这是我的代码:
d= {}
with open("test.txt", 'r') as f:
l = f.readlines()
for line in l:
(key,val) = line.split()
d[key]=val
我收到错误:
too many values to unpack error
最佳答案
您还可以使用此方法:
d = {}
with open("test.txt", 'r') as f:
l = f.readlines()
i = 0
while i < len(l):
d[l[i].replace("\n","")] = l[i+1].replace("\n","")
i += 2
关于python - 来自文本文件的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931246/