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

2024-04-25 00:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这意味着每次更新时分数都会被覆盖,如果分数属于某个学生数,我有没有办法对其求和?你知道吗

类似于:

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 

Tags: andofthetoinnumberfordata
2条回答

您可以使用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]}

如果您想更进一步sumgrade,您可以使用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}

尝试此操作,当分配给字典时,查看该值是否存在,如果不存在,则将其设置为0。再加上:

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

相关问题 更多 >