-1

How to add the values of two dictionary ? Ex :

a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}

result must be

c = {'a':11,'b':12,'c':21}
Christopher Moore
  • 3,071
  • 4
  • 30
  • 46
Rajakumar
  • 139
  • 2
  • 11
  • generally when you ask a question you should include what you have tried and why it's not working. while some individuals may be happy to write code for you, stack overflow is not a code writing service.. – Aaron Feb 24 '17 at 18:29

2 Answers2

5

You can easily add two dictionaries by using Counter class of collections library for ex:

from collections import Counter

a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}

a = Counter(a)
b = Counter(b)
c = dict(a + b)
print c

OUTPUT

{'c': 21, 'b': 12, 'a': 11}
Anand Tripathi
  • 14,556
  • 1
  • 47
  • 52
1

Next some please show some effort..

a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}

c = {k: a[k] + b[k] for k in a}  
print(c)  # {'c': 21, 'b': 12, 'a': 11}

The above works fine if we assume that a and b have the same keys.

If that is not the case, you can try the following:

a = {'a': 10, 'b': 11, 'c': 20, 'h': 5}
b = {'a': 1, 'b': 1, 'c': 1, 'd': 12}

all_keys = set(a.keys())  # in Python 3 it can be simplified as `all_keys = set(a)`
all_keys.update(b.keys()) # in Python 3 it can be simplified as `all_keys.update(b)`
c = {k: a.get(k, 0) + b.get(k, 0) for k in all_keys}
print(c)  # {'c': 21, 'h': 5, 'a': 11, 'b': 12, 'd': 12}

Notice that i am using get on both dictionaries to skip the check on the existence of the key.

Ma0
  • 15,057
  • 4
  • 35
  • 65