Home > other >  Python. How to merge two dictionaries with the same keys?
Python. How to merge two dictionaries with the same keys?

Time:01-27

I have two dicts:

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

and i want to get:

{'a': 2, 'b': 2, 'c': 5}

i used {**a, **b} but it return:

{'a': 2, 'b': 2, 'c': 5, 'd': 4}

Help me please exclude keys from b which not in a with the simplest and fastest way.

i have python 3.7

CodePudding user response:

You have to filter the elements of the second dict first in order to not add any new elements. I got two possible solutions:

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

for k,v in b.items():
    if (k in a.keys()):
        a[k] = v

print(a)
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}

a.update([(k,v) for k, v in b.items() if k in a.keys()])

print(a)

Output for both:

{'a': 2, 'b': 2, 'c': 5}

CodePudding user response:

I think a comprehension is easy enough:

{ i : (b[i] if i in b else a[i]) for i in a }
  •  Tags:  
  • Related