Python: Updating one key of the pair adding the previous value to the new one - Dictionary/Hash -


in problem giving sequence of pairs: «number of student» «grade(partial)», gives final grade of students ordered highest grade lowest, , students same grade orders them using student number lower 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 code have far:

nice={}  try:      open('grades.txt') file:         data = file.readlines()  except ioerror ioerr:     print(str(ioerr))   each_line in data:     (number, grade) = each_line.split()     nice[number]=grade   num,grade in sorted(nice.items()):     print(num,grade) 

output get:

10885 10 60000 4 70000 4 

which means grade being overriden everytime updates, there way can sum grade if belongs student number instead of overidding it?

something of likes of:

for num,grade in sorted(nice.items()):     if(num in finaldic): //finaldic being new dicionary create         //find number , update grade adding existent      else():         //add new number , grade 

yet believe main problem of code lies around here:

    each_line in data:         (number, grade) = each_line.split()         nice[number]=grade  

try this, when assigned dictionary, see if value exists , if not, set 0. add it:

for each_line in data:   (number, grade) = each_line.split()   if number not in nice:       nice[number] = 0   nice[number] += int(grade) 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -