[英]How to add values from dictionaries in another dictionary?
I'm so lost in this small program I want to build... I have a scoreboard dictionary where I want to add scores from another dictionary. 我迷失在这个我想要建立的小程序中...我有一个记分板词典,我想从另一个字典中添加分数。 My code is looking something like this: 我的代码看起来像这样:
Edit: I have to add scores, not replace. 编辑:我必须添加分数,而不是替换。
def addScore(scorebord, scores):
# add values for common keys between scorebord and scores dictionaries
# include any keys / values which are not common to both dictionaries
def main():
scorebord = {}
score = {'a':1,
'b':2,
'c':3}
addScore(scorebord, score)
if __name__ == "__main__":
main()
Does anyone know how to write this function? 有谁知道如何写这个功能?
I am going to assume that when you add the dictionaries, you may have duplicate keys in which you can just add the values together. 我将假设当您添加词典时,您可能有重复的键,您可以在其中将值一起添加。
def addScore(scorebord, scores):
for key, value in scores.items():
if key in scorebord:
scorebord[key] += value
else:
scorebord[key] = value
def main():
scorebord = {}
score = {'a':1,
'b':2,
'c':3}
addScore(scorebord, score)
if __name__ == "__main__":
main()
collections.Counter
is designed specifically to count positive integers: collections.Counter
专门用于计算正整数:
from collections import Counter
def addScore(scorebord, scores):
scorebord += scores
print(scorebord)
def main():
scorebord = Counter()
score = Counter({'a': 1, 'b': 2, 'c': 3})
addScore(scorebord, score)
main()
# Counter({'c': 3, 'b': 2, 'a': 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.