0

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

tripleee
  • 158,107
  • 27
  • 234
  • 292
pirogan
  • 11
  • 1
  • Does this answer your question? [How do I merge two dictionaries in a single expression (take union of dictionaries)?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-take-union-of-dictionari) – tripleee Jan 27 '22 at 10:52

2 Answers2

1

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}
JANO
  • 2,544
  • 2
  • 13
  • 23
0

I think a comprehension is easy enough:

{ i : (b[i] if i in b else a[i]) for i in a }
kirjosieppo
  • 624
  • 2
  • 16