我有这个文本文件:
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
我得到了错误:
太多值无法解压缩错误
答案 0 :(得分:1)
i = 0
d = {}
prev_key = None
for line in l:
if i % 2 == 0:
prev_key = line
else:
d[prev_key] = line
i += 1
答案 1 :(得分:1)
您也可以使用这种方法:
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
答案 2 :(得分:1)
在原始代码中,您使用f.readlines()
一次读取文件中的所有行,然后拆分每一行。问题在于,并不是每行都给您一个包含两个元素的列表,所以key, val = line.split()
给您一个values to unpack
,因为您试图将单个元素列表分配给两个项目。例如a,b = [2]
会导致这种错误。
In [66]: a,b = [2]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-66-f9f79b7d1d3c> in <module>
----> 1 a,b = [2]
ValueError: not enough values to unpack (expected 2, got 1)
为避免这种情况,我们仅遍历读取的行,每个偶数元素都是键,而每个奇数元素都是字典中的值。
dct = {}
with open("file.txt", 'r') as f:
l = f.readlines()
idx = 0
while idx < len(l):
#Even element is key, Odd element is value
key = l[idx].strip()
value = l[idx+1].strip()
dct[key] = value
idx+=2
#{'English': 'hello bye', 'italian': 'ciao hola', 'spanish': 'hola chao'}
或更简单的使用dict-comprehension解决方案是
l = []
with open("file.txt", 'r') as f:
l = f.readlines()
#This will be a list of tuples, with the first element of tuple being the key #and second value being the value
#Keys are obtained by slicing all even indexes, and values by slicing all odd indexes
key_value_tups = zip(l[::2], l[1::2])
#[('English \n', 'hello bye \n'), ('italian \n', 'ciao hola\n'), ('spanish\n', 'hola chao\n')]
#Iterate through the tuples and create the dict via dict-comprehension
dct = {key.strip() : value.strip() for key, value in key_value_tups}
print(dct)
#{'English': 'hello bye', 'italian': 'ciao hola', 'spanish': 'hola chao'}
答案 3 :(得分:0)
您可以在一行中完成它:
with open("test.txt", 'r') as f:
lines = f.readlines()
dict( zip( lines[::2], lines[1::2] ) )
lines[::2]
将为您提供lines
的所有具有偶数索引的元素 lines[1::2]
将为您提供lines
的所有具有奇数索引的元素
zip
将根据两个列表创建一个迭代器(list1 elem, list2 elem)
dict
将迭代器中的每个元组(key, value)
用作字典项并创建字典
那一行相当于:
keys = []
values = []
for index, elem in enumerate(lines):
if index % 2 == 0:
keys += [elem]
else:
values += [elem]
d = {}
for key, val in zip(keys, values):
d[key] = val
答案 4 :(得分:-1)
通过zip()
使用字典理解:
with open("test.txt", 'r') as f:
l = f.readlines()
d = {x: y for x, y in zip(l[::2], l[1::2])}