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?
updated = {**default, **parsed}
, starting from python 3.9 (PEP 0584) you can use alsoupdated = default | parsed
– Gainor