1

Suppose there are 2 dictionaries:

A = {'a':1, 'b':2, 'c':3}
B = {'c':2, 'd':2, 'e':4}

How do I merge them together to obtain:

C = {'a':1, 'b':2, 'c':5, 'd':2, 'e':4}

I know that A.update(B) will give me a merged dictionary but the value that I want for 'c' in A would be over-written by the value held by 'c' in B instead of being added.

MSeifert
  • 145,886
  • 38
  • 333
  • 352

3 Answers3

1
A = {'a':1, 'b':2, 'c':3}
B = {'c':2, 'd':2, 'e':4}
C = {}

for key in A:
    C[key] = A[key] + B.get(key,0)

for key in B:
    try:
        C[key]
    except:
        C[key] = B[key]

print(C)

And thus you will get the required combined dict.

Animesh Sharma
  • 3,258
  • 1
  • 17
  • 33
1

Maybe the easiest way is to use a Counter:

from collections import Counter

A = {'a':1,'b':2,'c':3} 
B = {'c':2,'d':2,'e':4}

C = dict(Counter(A) + Counter(B))

print(C)
# {'a': 1, 'b': 2, 'c': 5, 'd': 2, 'e': 4}
MSeifert
  • 145,886
  • 38
  • 333
  • 352
-1

You can do the following

A = {'a':1,'b':2,'c':3}
B = {'c':2,'d':2,'e':4}
C = {}
keys_from_a = A.keys()
keys_from_b = B.keys()

total_keys = keys_from_a + keys_from_b
sort(total_keys)

for k in total_keys:
     if A[k]:
          C[k] = A[k]
     elif B[k]:
          C[k] = B[k]
     else:
          continue
print(c)
Mike Tung
  • 4,735
  • 1
  • 17
  • 24
  • keys cannot really be added. can they ? – Dilsher Bhat Apr 30 '17 at 03:36
  • I don't think this will produce the desired result. Moreover, A[k] will raise KeyError if k is not present A. So, either use has_key(k) or .get(k) – Animesh Sharma Apr 30 '17 at 03:37
  • In a more general case you'd be right but again if you know the dicts up front it doesn't matter. also the `keys()` method returns a list of all the keys – Mike Tung Apr 30 '17 at 03:38
  • (1) `keys()` only returns a list of keys in ancient Python. (2) `sort(total_keys)` will give a nameerror. (3) You never actually do any addition here. – DSM Apr 30 '17 at 03:40
  • @MikeTung The question was tagged python 3.6 (I removed the tag because there was nothing 3.6 specific about the question) and there the `keys()` aren't lists. So: No, they can't be added. – MSeifert Apr 30 '17 at 03:40
  • Yes. But total_keys contains keys from A and B. Obviously, the keys from B won't be present in A. And A[k] will be executed before B[k], thereby raising KeyError. – Animesh Sharma Apr 30 '17 at 03:41