简体   繁体   English

将列表从.txt文件转换为字典

[英]Converting a list from a .txt file into a dictionary

Ok, I've tried all the methods in Convert a list to a dictionary in Python , but I can't seem to get this to work right. 好的,我已经尝试了Python中将列表转换为字典中的所有方法,但似乎无法正常工作。 I'm trying to convert a list that I've made from a .txt file into a dictionary. 我正在尝试将我从.txt文件制作的列表转换成字典。 So far my code is: 到目前为止,我的代码是:

import os.path
from tkinter import *
from tkinter.filedialog import askopenfilename
import csv


window = Tk()
window.title("Please Choose a .txt File")
fileName = askopenfilename()

classInfoList = []
classRoster = {}
with open(fileName, newline = '') as listClasses:
    for line in csv.reader(listClasses):
        classInfoList.append(line)

The .txt file is in the format: professor class students .txt文件的格式为:教授班学生

An example would be: Professor White Chem 101 Jesse Pinkman, Brandon Walsh, Skinny Pete 例如:White Chem 101教授Jesse Pinkman,Brandon Walsh,Skinny Pete

The output I desire would be a dictionary with professors as the keys, and then the class and list of students for the values. 我想要的输出将是一本以教授为键的字典,然后是值的班级和学生名单。

OUTPUT: 
{"Professor White": ["Chem 101", [Jesse Pinkman, Brandon Walsh, Skinny Pete]]}

However, when I tried the things in the above post, I kept getting errors. 但是,当我尝试以上文章中的内容时,我不断遇到错误。

What can I do here? 我在这里可以做什么?

Thanks 谢谢

Since the data making up your dictionary is on consecutive lines, you will have to process three lines at once. 由于构成字典的数据是连续的,因此您必须一次处理三行。 You can use the next() method on the file handle like this: 您可以在文件句柄上使用next()方法,如下所示:

output = {}
input_file = open('file1')
for line in input_file:
    key = line.strip()
    value = [next(input_file).strip()]
    value.append(next(input_file).split(','))
    output[key] = value
input_file.close()

This would give you: 这将为您提供:

{'Professor White': ['Chem 101',
                     ['Jesse Pinkman, Brandon Walsh, Skinny Pete']]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM