Python: How to merge and update dictionary without changing old dictionary? New method in Python 3.9.
In Python 3.9 there is new method to create new dictionary with updated values and keep old dictionary without updates - using operator |
new_dict = old_dict | dict_with_updates
With list comprehension it will be
arg = [ d | {"a": i} for i in c]
Full example
d = {"a": 1, "b": 10}
c = [3, 4, 5]
arg = [ d | {"a": i} for i in c]
print(arg)
BTW: There is also |=
to update existing dictionary
old_dict |= dict_with_updates
In older version you can do
Instead of |=
old_dict.update(dict_with_updates)
Instead of |
new_dict = {**old_dict, **dict_with_updates}
If you like it
Buy a Coffee
