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

时间:2017-04-16 14:28:56

标签: python file dictionary file-read

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

Animals
Dog
Cat
Bird
Cities
Paris
London
Chicago

进入字典。 (第一行成为键后跟三行值,依此类推)它应该是这样的:

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

请帮帮我!

5 个答案:

答案 0 :(得分:1)

以下是使用islice的解决方案,可帮助您选择接下来的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

答案 1 :(得分:0)

这应该有效:

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)

答案 2 :(得分:0)

尝试这样的事情:

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

答案 3 :(得分:0)

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

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']} 

答案 4 :(得分:0)

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