Skip to content Skip to sidebar Skip to footer

When To Use Dictionary | (merge) Vs |= (update) Operator

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

Solution 1:

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.

Post a Comment for "When To Use Dictionary | (merge) Vs |= (update) Operator"