Dec-15-2017, 10:29 PM
Hello!
My code is supposed to read lines from a file that contains several attributes: assignment number, assignment name, grade, total, and weight. Each line of the file has this format.
My code reads the lines and turns it into a nested dictionary. Currently, the code seems to be looping and overwriting the key values of the inner dictionary.
Here is the file it's reading from:
The correct output:
Thank you for your help! I've been trying to figure this out for a few days and just wish to understand.
My code is supposed to read lines from a file that contains several attributes: assignment number, assignment name, grade, total, and weight. Each line of the file has this format.
My code reads the lines and turns it into a nested dictionary. Currently, the code seems to be looping and overwriting the key values of the inner dictionary.
Here is the file it's reading from:
1 assignment_1 85 100 0.25 2 test_1 90 100 0.25 3 exam_1 95 100 0.5The code should return a nested dictionary with the assignment name as the key, and the inner dictionary having the keys "number", "grade", "total", and "weight" for each line.
The correct output:
Output:{'assignment_1': {'total': 100, 'number': 1, 'grade': 85, 'weight': 0.25}, 'test_1': {'total': 100, 'number': 2, 'grade': 90, 'weight': 0.25}, 'exam_1': {'total': 100, 'number': 3, 'grade': 95, 'weight': 0.5}}
Here is my code:def reader(filename): file_reader = open(filename) results = [] innerdict = {} outerdict = {} for line in file_reader: parts = line.split(" ") line_tuple = (int(parts[0]), parts[1], int(parts[2]), int(parts[3]), float(parts[4])) key = line_tuple[1] outerdict[key] = innerdict innerdict["number"] = line_tuple[0] innerdict["grade"] = line_tuple[2] innerdict["total"] = line_tuple[3] innerdict["weight"] = line_tuple[4] return outerdictIt returns this output:
Output:{'assignment_1': {'number': 3, 'weight': 0.5, 'total': 100, 'grade': 95}, 'test_1': {'number': 3, 'weight': 0.5, 'total': 100, 'grade': 95}, 'exam_1': {'number': 3, 'weight': 0.5, 'total': 100, 'grade': 95}}
I believe I am somewhat close, I just do not know how to preserve the values of the inner dictionary once it loops over a line. Thank you for your help! I've been trying to figure this out for a few days and just wish to understand.