How to add values from dictionaries in another dictionary?

Viewed 63

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?

3 Answers
def addScore(scorebord, scores):
    scorebord.update(scores)

See more about dictionary update here

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:

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})
Related