Combine two dictionaries with preference to one of them - [duplicate]
Asked Answered
C

3

19

I have two dictionaries

One:

default = {"val1": 10, "val2": 20, "val3": 30, "val4": 40}

Two:

parsed = {"val1": 60, "val2": 50}

Now, I want to combine these two dictionaries in such a way that values for the keys present in both the dictionaries are taken from the parsed dictionary and for rest of the keys in default and their values are put in to the new dictionary.

For the above given dictionary the newly created dictionary would be,

updated = {"val1": 60, "val2": 50, "val3": 30, "val4": 40}

The obvious way to code up this would be to loop through the keys in default and check if that is present in parsed and put then into a new list updated, and in the else clause of the same check we can use values from default.

I am not sure if this is a pythonic way to do it or a much cleaner method. Could someone help on this?

Circumvent answered 2/1, 2021 at 12:53 Comment(3)
updated = {**default, **parsed}, starting from python 3.9 (PEP 0584) you can use also updated = default | parsedGainor
Nope. My question is on giving preference to a dictionary over another in a combine expression.Circumvent
Not sure why the comment was deleted. The duplicate target does answer the question. See, for example, the accepted answer: "The desired result is to get a new dictionary (z) with the values merged, and the second dictionary's values overwriting those from the first." The answers here don't add anything new and just repeat the solutions given in the duplicate target.Ostend
A
20

You can create a new dict with {**dict1,**dict2} where dict2 is the one that should have priority in terms of values

>>> updated = {**default, **parsed}
>>> updated
{'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}
Apeman answered 2/1, 2021 at 12:57 Comment(0)
E
11

First, create a copy of the dict with values you want to keep using the dict.copy() method Then, use the dict.update() method to update the other dict into the create dict copy:

default = {"val1": 10, "val2": 20, "val3": 30, "val4": 40}
parsed = {"val1": 60, "val2": 50}

updated = default.copy()
updated.update(parsed)

print(updated)

Output:

{'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}
Exhaustion answered 2/1, 2021 at 12:56 Comment(0)
O
2

Can also:

updated = {**default, **parsed}

Outputs:

{'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}
Oaken answered 2/1, 2021 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.