12
dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}

result {a:8, b:7, c:1}

How can I get the result?

Joshua
  • 40,822
  • 8
  • 72
  • 132
Peter
  • 315
  • 2
  • 3
  • 6
  • 2
    Possible duplicate of [Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?](https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe) – i2_ May 03 '19 at 08:21

6 Answers6

24

this is a one-liner that would do just that:

dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}

result = {key: dict1.get(key, 0) + dict2.get(key, 0)
          for key in set(dict1) | set(dict2)}
# {'c': 1, 'b': 7, 'a': 8}

note that set(dict1) | set(dict2) is the set of the keys of both your dictionaries. and dict1.get(key, 0) returns dict1[key] if the key exists, 0 otherwise.


this works on a more recent python version:

{k: dict1.get(k, 0) + dict2.get(k, 0) for k in dict1.keys() | dict2.keys()}
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
16

You can use collections.Counter which implements addition + that way:

>>> from collections import Counter
>>> dict1 = Counter({'a': 5, 'b': 7})
>>> dict2 = Counter({'a': 3, 'c': 1})
>>> dict1 + dict2
Counter({'a': 8, 'b': 7, 'c': 1})

if you really want the result as dict you can cast it back afterwards:

>>> dict(dict1 + dict2)
{'a': 8, 'b': 7, 'c': 1}
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 2
    this implementation . has a problem it's not counting values that are zeros – Espoir Murhabazi Sep 27 '18 at 10:35
  • Actually it [only keeps positive values](https://github.com/python/cpython/blob/5ee21732ee609805c60c60691119f3d509d50cd5/Lib/collections/__init__.py#L736), i.e. `Counter(a=0, b=1) + Counter(b=-2) == Counter()` (`+` gives an empty counter here). – a_guest Jun 20 '19 at 19:45
0

Here is a nice function for you:

def merge_dictionaries(dict1, dict2):
    merged_dictionary = {}

    for key in dict1:
        if key in dict2:
            new_value = dict1[key] + dict2[key]
        else:
            new_value = dict1[key]

        merged_dictionary[key] = new_value

    for key in dict2:
        if key not in merged_dictionary:
            merged_dictionary[key] = dict2[key]

    return merged_dictionary

by writing:

dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}
result = merge_dictionaries(dict1, dict2)

result will be:

{'a': 8, 'b': 7, 'c': 1}
OuuGiii
  • 1,053
  • 1
  • 11
  • 31
0

A quick dictionary comprehension that should work on any classes which accept the + operator. Performance might not be optimal.

{
    **dict1,
    **{ k:(dict1[k]+v if k in dict1 else v)
        for k,v in dict2.items() }
}
rovyko
  • 4,068
  • 5
  • 32
  • 44
0
Here is another approach but it is quite lengthy!

d1 = {'a': 5, 'b': 7}
d2 = {'a': 3, 'c': 1}

d={}
for i,j in d1.items():
    for k,l in d2.items():
        if i==k:
            c={i:j+l}
            d.update(c)
for i,j in d1.items():
    if i not in d:
        d.update({i:j})
for m,n in d2.items():
    if m not in d:
        d.update({m:n})
Loki
  • 33
  • 1
  • 9
0

Think it's much simpler.

a={'a':3, 'b':5}

b= {'a':4, 'b':7}

{i:a[i]+b[i] for i in a.keys()}

Output: {'a': 7, 'b': 12}