简体   繁体   中英

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. I'm trying to convert a list that I've made from a .txt file into a dictionary. 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

An example would be: Professor 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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