How to marge/add two or more Python dictionaries?

Question:

Lets say I have two python dictionaries:

dct_01 = {'a': 1, 'b': 2, 'c': 3}
dct_02 = {'a': 2, 'b': 1, 'c': 3, 'd': 4}

and I want:

dct_03 = {'a': 3, 'b': 3, 'c': 3, 'd': 4}

If both the dictionary have same key->value pair, it should remain same, if there is same key with different values it should add up.

How can I do this?

Asked By: Md. Zakir Hossan

||

Answers:

m = {}
for i in dct_01.keys()|dct_02.keys():
   v1 = dct_01.get(i)
   v2 = dct_02.get(i)
   if v1==v2: m[i] = v1
   elif v1 is None: m[i] = v2
   elif v2 is None: m[i] = v1
   else: m[i] = v1+v2

m
{'d': 4, 'c': 3, 'a': 3, 'b': 3}
Answered By: onyambu

You can use a dictionary comprehension with a custom function. We calculate the union of dictionary keys via set(dct_01) | set(dct_02) and iterate over them.

dct_01 = {'a': 1, 'b': 2, 'c': 3}
dct_02 = {'a': 2, 'b': 1, 'c': 3, 'd': 4}

def calc_val(d1, d2, k):
    val1 = d1.get(k, 0)
    val2 = d2.get(k, 0)
    if val1 == val2:
        return val1
    return val1 + val2

res = {k: calc_val(dct_01, dct_02, k) for k in set(dct_01) | set(dct_02)}

print(res)

{'b': 3, 'a': 3, 'c': 3, 'd': 4}
Answered By: jpp
dct_01 = {'a': 1, 'b': 2, 'c': 3}
dct_02 = {'a': 2, 'b': 1, 'c': 3, 'd': 4}
dct_03 = {**dct_01,**dct_02}
print(dct_03)
Answered By: Yash Shapara
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.