Python 添加不同字典的键值并将其存储到另一个字典中
我有类似的东西Python 添加不同字典的键值并将其存储到另一个字典中,python,dictionary,slice,Python,Dictionary,Slice,我有类似的东西 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 = {'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}
.....
.....
依此类推,直到螺柱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
使用
dictionary.iteritems()
迭代每个字典并将它们附加到第一个字典中
for k,v in dict.iteritems():
dict2[k] = v
或者您可以使用dictionary.update()
:
使用
dictionary.iteritems()
迭代每个字典并将它们附加到第一个字典中
for k,v in dict.iteritems():
dict2[k] = v
或者您可以使用dictionary.update()
:
您可以为此使用collections.Counter,然后将每个字典更新到该计数器中。范例-
from collections import Counter
s1c = Counter(stud_1)
s1c.update(stud_2)
s1c.update(stud_3)
.
.
.
Counter是dict的一个子类,所以以后可以将s1c用作一个简单的字典
更新计数器时,将从传入的字典/计数器中添加值,而不是覆盖值。您可以使用collections.Counter进行此操作,然后将每个字典更新到该计数器中。范例-
from collections import Counter
s1c = Counter(stud_1)
s1c.update(stud_2)
s1c.update(stud_3)
.
.
.
Counter是dict的一个子类,所以以后可以将s1c用作一个简单的字典
更新计数器时,将从传入的字典/计数器中添加值,而不是覆盖。是否可以发布所需的准确输出?是否可以发布所需的准确输出?如何添加不同的字典值?您可以在dictionary.iteritems()中对k,v使用
:dict[k]=v
或者您可以使用另一种方法,即dict1.update(dict2)
。如何添加不同的字典值?您可以在dictionary.iteritems()中为k,v使用:dict[k]=v
或者您可以使用另一种方法,即dict1.update(dict2)
。效果非常好。但是我如何把它转换回字典呢?你实际上不需要,但是如果你真的想,试试-dict(s1c)。是的,它很有效。那么max(s1c,key=s1c.get)在计数器的情况下起作用了吗?是的,它起作用了。就像我说的,计数器是dict的一个子类,所以几乎所有你能用dict做的事情,你都可以用计数器来做。工作起来很有魅力。但是我如何把它转换回字典呢?你实际上不需要,但是如果你真的想,试试-dict(s1c)。是的,它很有效。那么max(s1c,key=s1c.get)在计数器的情况下起作用了吗?是的,它起作用了。就像我说的,计数器是dict的一个子类,所以几乎所有可以用dict做的事情,都可以用计数器来做。