d3 = dict(d1, **d2)
I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I woul
Starting in Python 3.9
, the operator | creates a new dictionary with the merged keys and values from two dictionaries:
# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d3 = d2 | d1
# d3: {'b': 2, 'c': 3, 'a': 1}
This:
Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.
Also note the |=
operator which modifies d2 by merging d1 in, with priority on d1 values:
# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d2 |= d1
# d2: {'b': 2, 'c': 3, 'a': 1}