将txt文件读入字典

Reading a txt file into a dictionary

我有一个这样的文本文件:

Ben
5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5 
Moose
5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0 
Reuven
5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3 

我需要将此 txt 文件转换为字典,其中每隔一行都是其后一行的键。 示例:

d = {'ben': 5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5, 
"moose":5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0, 
"Reuven":5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3}

您可以通过以下方式获取您想要的

这是如何运作的

enumerate 为每次迭代提供一个(索引,值)对,您可以使用文件对象 f 直接遍历文件中的每一行。通过这种方式,如果您担心的话,您不必及时将整个文件读入内存。

i % 2 == 0 表示该行是偶数行,因此将成为您字典中的关键字。然后 else 部分将使用此键添加奇数行。

如果您不想要列表,可以将 line.strip().split() 更改为 line

f = open('file.txt')

res = {}

for i, line in enumerate(f):
    if i % 2 == 0:
        key = line.strip()
    else:
        res[key] = line.strip().split()

print(res)
f.close()

输出

{'Ben': ['5', '0', '0', '0', '0', '0', '0', '1', '0', '1', '-3', '5', '0', '0', '0', '5', '5', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '0', '1', '0', '-5', '0', '0', '5', '5', '0', '5', '5', '5', '0', '5', '5', '0', '0', '0', '5', '5', '5', '5', '-5'], 'Moose': ['5', '5', '0', '0', '0', '0', '3', '0', '0', '1', '0', '5', '3', '0', '5', '0', '3', '3', '5', '0', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '3', '5', '0', '0', '0', '0', '0', '5', '-3', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '5', '5', '0', '3', '0', '0'], 'Reuven': ['5', '-5', '0', '0', '0', '0', '-3', '-5', '0', '1', '-5', '5', '0', '1', '0', '1', '-3', '1', '-5', '0', '0', '0', '0', '0', '0', '3', '0', '0', '0', '0', '-5', '1', '0', '1', '0', '-5', '0', '3', '-3', '3', '0', '1', '5', '1', '0', '0', '0', '0', '0', '1', '3', '1', '5', '1', '3']}

代码

with open('input.txt', 'r') as infile:
    data = infile.readlines()   # data is a list with lines of file
    # Use slicing and zip with dictionary comprehension
    # data[::2] are even lines of data
    # data[1::2] are odd lines of data
    # use rstrip to get rid of trailing '\n'
    result = {x.rstrip():y.rstrip() for x, y in zip(data[0::2], data[1::2])}

结果包含

{'Ben': '5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5',
 'Moose': '5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0',
 'Reuven': '5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3'}