Reputation: 21
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}
How to exclude keys from b
which are not in a
using the simplest and fastest way.
I am using python 3.7.
Upvotes: 0
Views: 139
Reputation: 1
Try this:
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4, 'c': 5}
result = {}
# Iterate over keys in dictionary a
for key, value in a.items():
# If key exists in dictionary b, choose the maximum value
if key in b:
result[key] = max(value, b[key])
else:
result[key] = value
print(result)
This should also work:
result = {key: max(a.get(key, 0), b.get(key, 0)) for key in a}
print(result)
Upvotes: 0
Reputation: 3076
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}
Upvotes: 2
Reputation: 647
I think a comprehension is easy enough:
{ i : (b[i] if i in b else a[i]) for i in a }
Upvotes: 2