我有这样的东西
stud_1 = {'stud_2' : 1, 'stud_3' : 3, 'stud_4' : 2,'stud_5' : 5,'stud_6' : 1,'stud_7' : 3,'stud_8' : 4,'stud_9' : 3}
stud_2 = {'stud_1' : 3, 'stud_3' : 2, 'stud_4' : 4,'stud_5' : 2,'stud_6' : 1,'stud_7' : 5,'stud_8' : 1,'stud_9' : 2}
stud_3 = {'stud_1' : 1, 'stud_2' : 5, 'stud_4' : 3,'stud_5' : 5,'stud_6' : 5,'stud_7' : 2,'stud_8' : 3,'stud_9' : 5}
stud_4 = {'stud_1' : 4, 'stud_2' : 3, 'stud_3' : 2,'stud_5' : 1,'stud_6' : 5,'stud_7' : 3,'stud_8' : 1,'stud_9' : 4}
.....
.....
以此类推直到stud_9 .值是每个学生获得的五分制分数
我想将键值相加并将其存储在另一个字典中。 喜欢添加键的值 stud_1在 stud_1 以外的词典中本身,然后将其存储在键为 stud_1 的新字典中.
我该怎么做?
编辑:
如果我这里只考虑这4个词典,最终的词典应该是
final_dict = {'stud_1' : 9 , 'stud_2' : 9 , 'stud_3' : 7, 'stud_4' : 9 ....} ## and so on according to the key value
请您参考如下方法:
您可以为此使用 collections.Counter ,然后将每个字典更新到该 Counter 中。示例 -
from collections import Counter
s1c = Counter(stud_1)
s1c.update(stud_2)
s1c.update(stud_3)
.
.
.
Counter 是 dict 的子类,因此您稍后可以将 s1c 用作简单的字典。
当您更新 Counter 时,值将从传入的字典/Counter 添加,而不是覆盖。
