Program B.py The values in a dictionary can be Python lists . Code a dictionary
ID: 3662522 • Letter: P
Question
Program B.py
The values in a dictionary can be Python lists. Code a dictionary named grades that uses a course name for each key and a list of test scores as the value for each key. For example, a course with key Psychology might have the list of test scores 88, 72, 94, 85 as its value. See also the output of Program C.py below. Your dictionary should consist of at least four courses, each with three to five test scores. When finished, serialize or pickle your dictionary object in a binary file. This program outputs only the message below to the screen.
OUTPUT
My semester grades were pickled.
Program C.py
This program should unpickle the binary file created by the program above and retrieve the dictionary. The dictionary should then be processed to display each course name and, on the same line, the test scores for each course and the average of these scores accurate to two decimal places. See sample output below. Strive to duplicate this output. Use a try block and except block as shown. You will need a counter and an accumulator to determine the averages. You can get it all done in the main function with two nested loops in the try block.
SAMPLE OUTPUT
My current classes and test grades are
Math test grades: 89 100 85 94 Average: 92.00 %
Science test grades: 97 56 73 90 79 Average: 79.00 %
Computer class test grades: 80 90 97 Average: 89.00 %
Morality test grades: 99 76 90 35 Average: 75.00 %
Explanation / Answer
I have put both the programs below:
Program B.py
import pickle
#A dictionary named grades
grades = {}
# Stuffing it with the data
grades["Math"] = [89, 100, 85, 94]
grades["Science"] = [97, 56, 73, 90, 79]
grades["Computer"] = [80, 90, 97]
grades["Morality"] = [99, 76, 90, 35]
#open a file, say grades.pickle in the write binary format,
#and dump the dictionary data in to it using pickle
with open('grades.pickle', 'wb') as f:
pickle.dump(grades, f)
#print the output
print "My semester grades were pickled."
Program C.py
import pickle
#open the pickled binary file in the read binary format,
#and unpickle it using the load function of pickle
with open("grades.pickle", 'rb') as f:
grades = pickle.load(f);
print "My current classes and test grades are"
#pick a course and its scores, find its average, and print them all
for (course, scores) in grades.iteritems():
counter = 0 #to find no of scores
accumulator = 0 #to find total score
print course, "test grades:",
for s in scores:
print s,
counter = counter + 1
accumulator = accumulator + s
print " Average:", format(accumulator/counter, '.2f'), "%"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.