I have to use a dictionary to create a database of students' grades on Python. It must contain the fields name, score1, score2 and score3. Then I have to create a fifth field called average and fill it with the weighted average of the previous grades ((score1x20 score2x30 score3x50)/100). I can only use List/dictionary comprehension.
my input looks like this:
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7]}
and I should have some like this as my output:
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7],'avg': [9, 8, 7]}
I am very new to Pyhton (programming) and I am having difficulty on understanding how to iterate on each item.
Appreciate the help!
CodePudding user response:
Here your solution below:
scores = {
'student': ['s1', 's2', 's3'],
's1': [9, 9, 9],
's2': [8, 8, 8],
's3': [7, 7, 7]
}
# So now we have to search for every
# key in 'student' and calculate our output
avg = [] # This is our output for "avg" key
for i in scores['student']: # In each iteration i is that key, which
# weighted average we want to calculate
current_score = scores[i]
avg.append((current_score[0] * 20 current_score[1] * 30 current_score[2] * 50) // 100)
# Right up there we're calculating your weighted average of the previous
# grades
# and appending it to avg list
scores['avg'] = avg
print(scores)
CodePudding user response:
scores = {'student': ['s1', 's2', 's3'], 's1': [9, 9, 9], 's2': [8, 8, 8], 's3': [7, 7, 7],'avg': [9, 8, 7]}
So what you want is to add this part:
'avg': [9, 8, 7]
Do you know how a Python dict
works?
>>> d = {'key': 'value'}
>>> d
{'key': 'value'}
>>> d['otherKey'] = 'otherValue'
>>> d
{'key': 'value', 'otherKey': 'otherValue'}
So guess what you have to do to add that part...
scores['avg'] = ...