If you are given a .txt file which contains these contents:
James Doe 2/16/96 IT210 A BUS222 B PHY100 C
John Gates 4/17/95 IT101 C MATH112 B CHEM123 A
Butch Thomas 1/28/95 CS100 C MATH115 C CHEM123 B
How can you get it so it takes the class names and grades and puts them into an empty dictionary while ignoring the rest? I have code set up to read the .txt file but got stuck. Any suggestions?
This is my code for opening the file:
def readFile():
new_dict = {}
myFile = open('Students.txt', 'r')
for line in myFile:
解决方案
Instead of making different variables for each student, why not use a list of dictionaries?
See the code below :
>>> dictList = []
>>> with open('Students.txt', 'r') as f:
for line in f:
elements = line.rstrip().split(" ")[3:]
dictList.append(dict(zip(elements[::2], elements[1::2])))
>>> dictList
[{'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}, {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}]
If you're looking to maintain the order as given in the txt file in the dictionary, then look into an OrderedDict.