Creating a dictionary from a .txt file using Python -
if given .txt file
contains these contents:
james doe 2/16/96 it210 bus222 b phy100 c john gates 4/17/95 it101 c math112 b chem123 butch thomas 1/28/95 cs100 c math115 c chem123 b
how can takes class names , grades , puts them empty dictionary while ignoring rest? have code set read .txt file
got stuck. suggestions?
this code opening file:
def readfile(): new_dict = {} myfile = open('students.txt', 'r') line in myfile:
instead of making different variables each student, why not use list of dictionaries?
see code below :
>>> dictlist = [] >>> open('students.txt', 'r') f: 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 maintain order given in txt file in dictionary, ordereddict
.
Comments
Post a Comment