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}

How to exclude keys from b which are not in a using the simplest and fastest way.

I am using python 3.7.

1

3 Answers 3

2

I think a comprehension is easy enough:

{ i : (b[i] if i in b else a[i]) for i in a }
2

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}
1
  • if (k in a.keys()): can be simplified to just if k in a: Commented May 11 at 2:59
0

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.