Python:更新一对中的一个键,将先前的值添加到新的值 - Dictionary/Hash

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

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.

例如。 输入:

10885 10
70000 6
70000 10
60000 4
70000 4
60000 4
10885 10

输出:

10885 20
70000 20
60000 8

这是我目前的代码:

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)

我得到的输出:

10885 10
60000 4
70000 4

这意味着每次更新时成绩都会被覆盖,我有什么办法可以 sum grade 如果它属于那个学号而不是覆盖它?

类似的东西:

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

但我认为我的代码的主要问题在于此:

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

试试这个,当分配给字典时,看这个值是否存在,如果不存在,将它设置为0。然后添加到它:

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

您可以使用 setdefault:

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.setdefault(number, []).append(int(grade))
print (nice)

这是输出:

{'10885': [10, 10], '70000': [6, 10, 4], '60000': [4, 4]}

如果您想更进一步 sum grade,您可以使用 dictionary comprehension,从 nice 创建一个新字典,如下所示:

nice_sum = {k:sum(v) for k,v in nice.items()}
print (nice_sum)

nice_sum的输出:

{'10885': 20, '70000': 20, '60000': 8}