17

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Rohan Asokan
  • 634
  • 4
  • 22
  • 5
    `updated = {**default, **parsed}`, starting from python 3.9 ([PEP 0584](https://www.python.org/dev/peps/pep-0584/)) you can use also `updated = default | parsed` – Olvin Roght Jan 02 '21 at 12:56
  • 1
    Nope. My question is on giving preference to a dictionary over another in a combine expression. – Rohan Asokan Jan 04 '21 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 Jan 05 '21 at 14:44

3 Answers3

15

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}
abc
  • 11,579
  • 2
  • 26
  • 51
10

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}
Red
  • 26,798
  • 7
  • 36
  • 58
2

Can also:

updated = {**default, **parsed}

Outputs:

{'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}
sheldonzy
  • 5,505
  • 9
  • 48
  • 86