从文本文件的字典

问题描述 投票:1回答:5

我有这个文本文件:

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

我收到错误:

解压错误的值太多了

python list dictionary
5个回答
0
投票

您也可以使用此方法:

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

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

0
投票

在原始代码中,您使用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'}

0
投票
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
投票

使用zip()使用字典理解:

with open("test.txt", 'r') as f:
    l = f.readlines()
    d = {x: y for x, y in zip(l[::2], l[1::2])}
© www.soinside.com 2019 - 2024. All rights reserved.