如何将字典中的值添加到另一本字典中?
How to add values from dictionaries in another dictionary?
我迷失在这个我想构建的小程序中...
我有一本记分牌字典,我想在其中添加另一本字典的分数。我的代码看起来像这样:
编辑:我必须添加分数,而不是替换。
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()
有人知道这个函数怎么写吗?
def addScore(scorebord, scores):
scorebord.update(scores)
查看有关词典更新的更多信息here
我假设当您添加字典时,您可能有重复的键,您可以将其中的值加在一起。
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
是专门用来统计正整数的:
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})
我迷失在这个我想构建的小程序中... 我有一本记分牌字典,我想在其中添加另一本字典的分数。我的代码看起来像这样:
编辑:我必须添加分数,而不是替换。
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()
有人知道这个函数怎么写吗?
def addScore(scorebord, scores):
scorebord.update(scores)
查看有关词典更新的更多信息here
我假设当您添加字典时,您可能有重复的键,您可以将其中的值加在一起。
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
是专门用来统计正整数的:
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})