Free cookie consent management tool by TermsFeed The merge operator ( | ) of Python dictionary class | Pythontic.com

The merge operator ( | ) of Python dictionary class

Operator:

| (Merge Operator)

Overview:

  • The merge operator or the union operator combines the contents of the two dictionaries.
  • The resultant dictionary contains the union of two key spaces k1, k2 and their corresponding values from the dictionaries d1, d2 where d1 is the current dictionary(self, this and other similar names are used to refer to the first operand) on to which d2(which is passed as a parameter) is merged.
  • If both the dictionaries d1 and d2 have the same keys the value from d1 is taken for the merge operation.

Merge operator of Python dictionary class

Operands:

d1 - Current dictionary object

d2 - Another dictionary object passed as a parameter

Return value:

The merged dictionary as a dict instance.

Example:

In this example the keys t1 to t5 in the new dictionary are given new values from the dictionary instance that is passed as a parameter.

# Example Python program that applies the
# merge operator (|) to combine two
# Python dictionaries

# Dictionary 1
day1Price = {"t1":65,
             "t2":67,
             "t3":65,
             "t4":67.5,
             "t5":70};

# Dictionary 2
day2Price = {"t1":64.9,
             "t2":67.5,
             "t3":65,
             "t4":67.51,
             "t5":72,
             "t6":71};

# Merge the two dictionaries
union = day1Price | day2Price;
print(union);

Output:

{'t1': 64.9, 't2': 67.5, 't3': 65, 't4': 67.51, 't5': 72, 't6': 71}

 


Copyright 2025 © pythontic.com