MrBacon314
MrBacon314

Reputation: 18

How To Merge Two Dictionaries With Common and Different Keys in Python?

I am trying to make a function that will take two dictionaries and merge them together. When I search for the solution, I can find ones that only work for dictionaries that only have common keys, or only have different keys, but not a solution to both.

Example of what I want below.

Input

x = {"a": 91, "b": 102}
y = {"b": 8, "c": True}

Output

z = {"a": 91, "b": 110, "c": True}

Upvotes: 0

Views: 136

Answers (1)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can do that with dictionary comprehension, dict.get method and set union between dict.key objects:

>>> z = {k: x[k] + y[k]
            if (k in x and k in y)
            else x.get(k) or y.get(k)
            for k in sorted(x.keys() | y.keys())}
>>> z
{'a': 91, 'b': 110, 'c': 1}

Upvotes: 1

Related Questions