0

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

Community
  • 1
  • 1
Blackwell
  • 85
  • 2
  • 10
  • How are the fields in `Professor White Chem 101 Jesse Pinkman, Brandon Walsh, Skinny Pete` separated? – shaktimaan Apr 30 '14 at 00:10
  • [['Professor White'], ['Chem 101'], ['Jesse Pinkman', ' Skinny Pete', ' Brandon Mayhew', ' Marti Nansen', ' Todd Schultz'], [], ['Professor Draven'], ['Crim 210'], ['Saul Goodman', ' Mike Ehrmantrau', ' Jesse Pinkman', ' Bruce Wayne', ' Gus Fring'], [],...etc. I need to get rid of th extra instances of [], too... – Blackwell Apr 30 '14 at 00:18

1 Answers1

1

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']]}
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • It's separated by enter, so professors on on the first line, class second line, students third line, repeat. – Blackwell Apr 30 '14 at 00:26
  • @Blackwell In that case you don't even need the csv module. Check my updated answer – shaktimaan Apr 30 '14 at 00:34
  • Indeed that worked. I'll have to research how next works. Thank you. – Blackwell Apr 30 '14 at 00:42
  • When you read a file, the lines in the file is returned as an iterator. `next()` is a method on any iterator. More here - https://docs.python.org/2/library/functions.html#next – shaktimaan Apr 30 '14 at 01:01