Dictionary Union Operators in Python

As of Python 3.9, the dict type will have two new union operators.

The merge operator | and the update operator |=.

The merge operator

The merge operator | takes two dictionaries and returns a new one.

Notice that all_brands has all the items of car_brands1 and car_brands2.

car_brands1 = {1: 'bmw', 2: 'mclaren', 3: 'ferrari'}
car_brands2 = {4: 'jeep', 5: 'toyota'}

all_brands = car_brands1 | car_brands2

print(all_brands)
{1: 'bmw', 2: 'mclaren', 3: 'ferrari', 4: 'jeep', 5: 'toyota'}

The update operator

The update operator |= updates the dictionary on the left side of the opertor with the items of the dictionary on the right side.

It doesn\’t generate a new dictionary.

car_brands1 = {1: 'bmw', 2: 'mclaren', 3: 'ferrari'}
car_brands2 = {4: 'jeep', 5: 'toyota'}

car_brands1 |= car_brands2

print(car_brands1)
{1: 'bmw', 2: 'mclaren', 3: 'ferrari', 4: 'jeep', 5: 'toyota'}

Dictionaries with the common keys

If both dictionaries have common keys, the one on the dictionary on the right side of the operator will prevail.

Notice both dictionaries have the key \’3\’, car_brands1 has \’ferrari\’ for key \’3\’ and car_brands2 has \’suzuki\’.

Since car_brands2 is on the right side of the operator, 3: 'suzuki' will be used in the final result.

car_brands1 = {1: 'bmw', 2: 'mclaren', 3: 'ferrari'}
car_brands2 = {3: 'suzuki', 4: 'jeep', 5: 'toyota'}

all_brands = car_brands1 | car_brands2

print(all_brands)
{1: 'bmw', 2: 'mclaren', 3: 'suzuki', 4: 'jeep', 5: 'toyota'}

This new feature is presented in PEP 584.

Watch on Youtube

You can also watch this content on Youtube: