字典中的清单

时间:2019-03-15 10:06:07

标签: python dictionary

我有一个这样的文本文件

10:45  a  b  c
     x 0  1  2
     y 4  5  6
     z 7  8  9

我想将x作为键,将0,1,2作为列表中的值。与y和z相同

 while(1):
    line = f.readline()



    if time in line:
        print (line)
        L1.append(line)
        for count,line in enumerate(f):

            if (i < 3):
                L1.append(line)
                print ("Line{} : {}".format(count,line.strip()))
                i=i+1


        #print(L1)
        for k in range(1):
            print(L1[k])
            test1 = L1[k]
            a1 = test1.split()
            print (a1[1])
            dict = {a1[1]: L1[k] for a1[1] in L1[k]}
            print (dict)

        for k in range(1,3):
            #print("hey")
            print (L1[k])               #will list the single row
            test = L1[k]                
            #print(test)                 
            a = test.split()            
            print (a[0])                
            dict = {a[0]:L1[k] for a[0] in L1[k]}
            print (dict)

你知道我在做什么错吗? 附言-我是python的新手

3 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

my_dict = {}
lines = f.readLines()
lines.pop(0)
for line in lines:
   line_list = line.split(' ')
   key = line_list.pop(0)
   my_dict.update({key: line_list})

答案 1 :(得分:0)

尝试一下

import string
start_found = False
result_dict = {}

for line in open("stack1_input.txt", mode='r'):
    if (line.startswith("10:45")):
        start_found = True
        continue
    if start_found == True:
        values = line.split()
        if len(values) == 4:
            result_dict[values[0]] = values[1:]

print (result_dict)

答案 2 :(得分:0)

这将完成我认为您需要的(假设文本文件存储在同一目录中,并用文件名替换“ test.txt”):

with open('test.txt', 'r') as values:
    contents = values.read().strip().split()
    new_dict = {}
    i = 4
    while i <= len(contents)-4:
        new_dict.update({contents[i]: contents[i+1:i+4]})
        i += 4

print(new_dict)

或者这,如果您想将值设为整数:

with open('test.txt', 'r') as values:
    contents = values.read().strip().split()
    new_dict = {}
    i = 4
    while i <= len(contents)-4:
        new_dict.update({contents[i]: [int(contents[i+1]),int(contents[i+2]),int(contents[i+3])]})
        i += 4

print(new_dict)