Homework Assignment 5 Instructions: Class name must be: HW5_yourName For example: Michael will name the python file of homework assignment 5 as HW5_Michael.py Grading Rubric: Code running and as per the required conditions and giving expected output = 10 points File named as per instructions = 1 point Comments in code = 4 points Problem: Average calculation of test scores using a Dictionary Write a program that reads a text file named Asg5_data.txt and stores the name of the student as the key of the dictionary element. The scores of each student will be stored in a list and the list will be the value of the key of Dictionary element. The dictionary with key-value pair is shown in Expected Output. The program should display average (average of 2 tests) for each student. Expected Output: Dictionary of student and their test scores is: {'michael': [25, 23], 'adelle': [26, 28], 'james': [24, 26], 'anders': [23, 29]} Dictionary of student and their average test scores is: {'michael': 24.0, 'adelle': 27.0, 'james': 25.0, 'anders': 26.0}
"""
Python version : 3.6
Python program that reads a text file named Asg5_data.txt and
stores the name
and the list of scores into the dictionary where keys are names of
students and
values are marks of the students. Then calculate and display the
sictionary of
average scores of each student.
"""
# open input file in read mode
file = open("Asg5_data.txt","r")
# create an empty dictionary
students = {}
# read a line from file
line = file.readline()
# loop to read till the end of file
while line:
# convert the string into list of strings
# strip is used to remove leading and trailing
whitespace from line string
# split is used to split the string using whitespace
as the delimiter
data = line.strip().split()
# extract the scores from data into score list
score = []
for i in range(1, len(data)):
score.append(int(data[i]))
# insert the data into the dictionary, where data[0]
contains the name of student and score is the list of scores
students[data[0]] = score
# read the next line
line = file.readline()
# close the file
file.close()
# display the dictionary
print('Dictionary of student and their test scores
is:\n',students)
# create an empty dictionary to store the average scores
avg_score = {}
# loop to calculate and insert average scores for each student into
the dictionary
for name in students:
avg_score[name] =
float(sum(students[name]))/len(students[name])
# display the average score dictionary
print('Dictionary of student and their average test scores
is:\n',avg_score)
#end of program
Code Screenshot:
Output:
Input file: Asg5_data.txt (values in a line are separated by a single space)
Output:
Get Answers For Free
Most questions answered within 1 hours.