我有这个文本文件:
English
hello bye
italian
ciao hola
spanish
hola chao
我想从每2个连续的行创建一个字典:
{
'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
我得到错误:
太多值无法解包错误
最佳答案
您也可以使用这种方法:
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