When to use dictionary | (merge) vs |= (update) operator

3.2k views Asked by At

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?

1

There are 1 answers

6
pho On BEST ANSWER

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 sets

a = {'hello', 'world', 'abc', 'def'}
b = {'abc', 'ghi', 'jkl'}

The operation a |= b is similar to a = a | b in much the same way as a += b is similar to a = a + b for lists.

a = {'hello', 'world', 'abc', 'def'}
al = list(a)
b = {'abc', 'ghi', 'jkl'}
bl = list(b)

print("Before: ", hex(id(a)), a)
a = a | b
print("After: ", hex(id(a)), a)
# Output: 
# Before:  0x1aa0186f128 {'world', 'def', 'abc', 'hello'}
# After:  0x1aa0186f828 {'world', 'ghi', 'hello', 'jkl', 'def', 'abc'}

print("Before: ", hex(id(al)), al)
al = al + bl
print("After: ", hex(id(al)), al)
# Output: 
# Before:  0x1aa0187a248 ['world', 'def', 'abc', 'hello']
# After:  0x1aa0366bdc8 ['world', 'def', 'abc', 'hello', 'jkl', 'abc', 'ghi']

Evidently, a is now a new set at a different location in memory.

a = {'hello', 'world', 'abc', 'def'}
al = list(a)
b = {'abc', 'ghi', 'jkl'}
bl = list(b)

print("Before", hex(id(a)), a)
a |= b
print("After", hex(id(a)), a)
# Output: 
# Before 0x1aa0186f128 {'world', 'def', 'abc', 'hello'}
# After 0x1aa0186f128 {'world', 'ghi', 'hello', 'jkl', 'def', 'abc'}

print("Before", hex(id(al)), al)
al += bl
print("After", hex(id(al)), al)
# Output:
# Before 0x1aa03646888 ['world', 'def', 'abc', 'hello']
# After 0x1aa03646888 ['world', 'def', 'abc', 'hello', 'jkl', 'abc', 'ghi']

In this case, a is still the old set at a same location in memory, but its contents have been updated.