简体   繁体   中英

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}

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM