When to use the merge vs update operators on dictionaries.
The following examples, while there are differences in how to call them, their output is the same.
a = {1: 'a', 2: 'b', 3: 'c', 6: 'in both'}
b = {4: 'd', 5: 'e', 6: 'but different'}
Using the update operator
z = a | b
print(z)
Output: {1: 'a', 2: 'b', 3: 'c', 6: 'but different', 4: 'd', 5: 'e'}
Using The merge operator
a |= b
print(a)
Output: {1: 'a', 2: 'b', 3: 'c', 6: 'but different', 4: 'd', 5: 'e'}
It seems as if the only advantage of the | (merge) is that it doesn't overwrite your old dictionary.
Is there something else that I am missing?
When should I choose to use one over the other?
The
|=
operator just updates your original dictionary with the result of the union operation. The|
operator returns a new dictionary that is the union of the two dicts. Let's say we have two setsThe operation
a |= b
is similar toa = a | b
in much the same way asa += b
is similar toa = a + b
for lists.Evidently,
a
is now a new set at a different location in memory.In this case,
a
is still the old set at a same location in memory, but its contents have been updated.