3

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
malahoeloe
  • 33
  • 3
  • 1
    `scorebord.update(scores)` – cs95 Dec 20 '18 at 19:20
  • `where I want to add scores from another dictionary`.. what do you mean by `add scores`? Do you mean overwrite scores, add scores where keys are the same, or something else? Can you [edit your question](https://stackoverflow.com/posts/53874786/edit) to give an example input with desired output? – jpp Dec 20 '18 at 19:26
  • @coldspeed This will replace, not add the scores, which may or may not be what OP is looking for – DeepSpace Dec 20 '18 at 19:28
  • 1
    @DeepSpace sure, then again it isn't clear what they meant. They said add but perhaps they referred to adding keys rather than summing/incrementing totals. – cs95 Dec 20 '18 at 19:30
  • Sorry I wasnt clear. I indeed meant adding scores to the first dictionary – malahoeloe Dec 20 '18 at 19:34
  • Possible duplicate of [How to merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression) – Anwarvic Dec 20 '18 at 19:34

3 Answers3

0
def addScore(scorebord, scores):
    scorebord.update(scores)

See more about dictionary update here

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
0

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()
Jae Yang
  • 479
  • 3
  • 13
0

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})
jpp
  • 159,742
  • 34
  • 281
  • 339