如何从文件中读取第一行作为键,将接下来的 3 行作为值列表读取到字典中,python

How to read the first line from a file as key and the next 3 lines as a list of values to a dictionary, python

我正在尝试阅读 txt 看起来像:

Animals
Dog
Cat
Bird
Cities
Paris
London
Chicago

入字典。 (第一行变成一个键,然后是三行值,依此类推)它应该看起来像这样:

{"Animals":["Dog","Cat","Bird"],"Cities":["Paris","London","Chicago"]

请帮帮我!

这应该有效:

ind = 0
my_dict = {}
my_list = []
for line in myfile:
    val = line.rstrip().split()[0]
    ind += 1
    if ind % 5 == 0:
        my_list = []
    if ind % 4 == 1:
        x = val
    else:
        my_list.append(val)

    if ind % 4 == 0:
            my_dict[x] = my_list

print(my_dict)

这是一个使用 islice 的解决方案,它可以帮助您 select 从文件中读取接下来的 n 行。

from itertools import islice

dic = {}

with open('file.txt', 'r') as f:
    while True:
        lines = list(islice(f, 4))
        lines = map(str.rstrip, lines)
        if not lines:
            break
        dic[lines[0]] = lines[1:]

print dic

这给出了您需要的结果:

{'Cities': ['Paris', 'London', 'Chicago'], 'Animals': ['Dog', 'Cat', 'Bird']}

更多关于islice

尝试这样的事情:

f = open('first.txt').readlines()
f = [i.strip('\n') for i in f]
datafile = [i.split() for i in f]


dct = {}


for i in range(len(datafile)):

    if i%4 == 0:

        new_lst = datafile[i+1:i+4]

        final_list = [b[0] for b in new_lst]

        print datafile[i][0]
        dct[datafile[i][0]] = final_list




print dct

这是另一种可能的解决方案:

fin = open(f, 'rb')

lines = [word.strip('\n') for word in fin.readlines()]

keys = [word.strip('\n') for idx, word in enumerate(fin.readlines()) if idx%4 == 0]

values = [lines[idx+1:idx+4] for idx, _ in enumerate(lines) if idx%4 == 0]

d = dict(zip(keys, values))

{'Animals': ['Dog', 'Cat', 'Bird'], 'Cities': ['Paris', 'London', 'Chicago']} 
import itertools

d = {}

with open("C:\path\to\text.txt", "r") as f:
    lines = f.readlines()

    # Separate keys from values
    keys = itertools.islice(lines, 0, None, 4)
    first_values = itertools.islice(lines, 1, None, 4)
    second_values = itertools.islice(lines, 2, None, 4)
    third_values = itertools.islice(lines, 3, None, 4)

    # Set keys and values
    for key in keys:
        key = key.rstrip()
        value1 = first_values.next().rstrip()
        value2 = second_values.next().rstrip()
        value3 = third_values.next().rstrip()

        # Create dict
        l = [value1, value2, value3]
        d[key] = l