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?

3
  • 5
    updated = {**default, **parsed}, starting from python 3.9 (PEP 0584) you can use also updated = default | parsed Commented Jan 2, 2021 at 12:56
  • 2
    Nope. My question is on giving preference to a dictionary over another in a combine expression. Commented Jan 4, 2021 at 15:42
  • 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.
    – Georgy
    Commented Jan 5, 2021 at 14:44

3 Answers 3

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}
0
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}
0
2

Can also:

updated = {**default, **parsed}

Outputs:

{'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}

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