In this problem giving a sequence of pairs: «number of the student» «grade(partial)», it gives us the final grade of the students ordered from the highest grade to the lowest, and for the students with the same grade it orders them using the student number from lower to higher.
eg. input:
10885 10
70000 6
70000 10
60000 4
70000 4
60000 4
10885 10
output:
10885 20
70000 20
60000 8
Here's the code I have so far:
nice={}
try:
with open('grades.txt') as file:
data = file.readlines()
except IOError as ioerr:
print(str(ioerr))
for each_line in data:
(number, grade) = each_line.split()
nice[number]=grade
for num,grade in sorted(nice.items()):
print(num,grade)
output I get:
10885 10
60000 4
70000 4
Which means the grade is being overriden everytime it updates, Is there I way I can sum the grade if it belongs to that certain student number instead of overidding it?
something of the likes of:
for num,grade in sorted(nice.items()):
if(num in finaldic): //finaldic being a new dicionary that we would create
//find the number and update the grade adding it to the existent
else():
//add new number and grade
Yet I believe the main problem of my code lies around here:
for each_line in data:
(number, grade) = each_line.split()
nice[number]=grade
Try this, when assigned to the dictionary, see if the value exists and if it does not, set it to 0. Then add to it:
for each_line in data:
(number, grade) = each_line.split()
if number not in nice:
nice[number] = 0
nice[number] += int(grade)