-2

I have the following two dictionaries

scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d

and

scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b

I need to collate and sum the scores for keys a and b in both dictionaries to produce the following output:

The answer could be 'done' using one of the following two methods (and there may be others I'd be interested to hear)

1. Using the creation of a new dictionary:

finalscores={a:30,b:30} #adds up the scores for keys a and b and makes a new dictionary

OR

2. update the scores2 dictionary (and add the values from scores1 to the scores2 corresponding respective values

An accepted answer would show both the above with any suitable explanation as well as suggest any more astute or efficient ways of solving the problem.

There was a suggestion on another SO answer that the dictionaries could simply be added:

print(scores1+scores2) Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

But I want to do this in the simplest method possible, without iterator imports or classes

I have also tried, but to no avail:

newdict={}
newdict.update(scores1)
newdict.update(scores2)
for i in scores1.keys():
    try:
        addition = scores[i] + scores[i]
        newdict[i] = addition

   except KeyError:
        continue
Abe
  • 1,357
  • 13
  • 31
Compoot
  • 2,227
  • 6
  • 31
  • 63
  • 1
    Welcome to SO. Unfortunately this isn't a code writing service. If you haven't had the opportunity, please read [ask] and [mcve]. You might want to work your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html) to get an idea of the tools available to help you solve your problems. – wwii Sep 14 '17 at 15:00
  • Actually, I cannot find information elsewhere on how to do this specific task - in terms of merging values from two different dictionaries. Surely it is a valid question that will help numerous other SO users – Compoot Sep 14 '17 at 15:06

1 Answers1

1

For the first solution:

scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d
scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b

finalscores=dict((key, sum([scores1[key] if key in scores1 else 0, scores2[key] if key in scores2 else 0])) for key in set(scores1.keys()+scores2.keys()))
print(finalscores)
# outputs {'a': 30, 'c': 30, 'b': 30, 'd': 10}

This iterates through a set of all keys in both dictionaries, creates a tuple with the values of the key in both dictionaries or 0 and then passes said tuple through the sum function adding the results. Finally, it generates a dictionary.

EDIT

In multiple lines, to understand the logic, this is what the one-liner does:

finalscores = {}
for key in set(scores1.keys()+scores2.keys()):
    score_sum = 0
    if key in scores1:
        score_sum += scores1[key]
    if key in scores2:
        score_sum += scores2[key]
    finalscores[key] = score_sum

For the second solution:

scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d
scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b

for k1 in scores1:
    if k1 in scores2:
        scores2[k1] += scores1[k1]  # Adds scores1[k1] to scores2[k1], equivalent to do scores2[k1] = scores2[k1] + scores1[k1]
    else:
        scores2[k1] = scores1[k1]

print(scores2)
# outputs {'a': 30, 'c': 30, 'b': 30, 'd': 10}
francisco sollima
  • 7,952
  • 4
  • 22
  • 38
  • Thanks so much - are you able to put solution 1 with the new dict in a format with indentation(on different lines). Very hard to follow the logic otherwise...Huge thanks! – Compoot Sep 14 '17 at 15:25
  • I'm sorry, force of habit. I added the code broken in multiple lines, so it's actually understandable. – francisco sollima Sep 14 '17 at 15:38
  • An error for the first: for key in set(round1scoresdict.keys()+round2scoresdict.keys()): TypeError: unsupported operand type(s) for +: 'dict_keys' and 'dict_keys' >>> – Compoot Sep 14 '17 at 16:13
  • Is `round1scoresdict` a `dict`? Because apparently `round1scoresdict.keys()` doesn't return a list, but a `dict_keys` object. Same with `round2scoresdict` – francisco sollima Sep 14 '17 at 16:15
  • And the second one works - answer accepted. Could you possibly comment the second answer please explaining this line in particular: scores2[k1] += scores1[k1] – Compoot Sep 14 '17 at 16:18