我迷上了这个想要构建的小程序... 我有一个记分牌字典,我想在其中添加其他字典的分数。我的代码看起来像这样:
编辑:我必须添加分数,而不是替换。
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()
有人知道如何编写此功能吗?
答案 0 :(得分:0)
def addScore(scorebord, scores):
scorebord.update(scores)
详细了解字典更新here
答案 1 :(得分:0)
我假设添加字典时,您可能有重复的键,您可以在其中将值加在一起。
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()
答案 2 :(得分:0)
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})