merging of two dictionaries

The merge operator | merges the contents of a dictionary with another dictionary and returns a new merged dictionary. The example Python program merges two dictionaries and prints the merged dictionary.

Dictionary Updated 18 Feb 2024 1 min read

Overview

  • The operator |, when applied on a Python dictionary object d1 with another dictionary object d2 as the parameter, merges the contents of both the dictionaries into a new dictionary and returns the new dictionary.

Example

python
# Example Python program that merges to python dictionaries

            # and prints the merged resultant dictionary

# Dictionary one

            d1 = {"US":"USD",

                 "Europe": "EUR",

                 "Japan": "JPY",

                 "England": "GBP",

                 "Australia": "AUD"}

# Dictionary two

            d2 = {"Canada": "CAD",

                  "Switzerland": "CHF",

                  "China": "CNH",

                  "Hong Kong": "HKD",

                  "New Zealand": "NZD"}

# Merge two dictionaries

            mergedDict = d1 | d2

# Print the merged dictionaries

            print(mergedDict)

Output

Output
{'US': 'USD', 'Europe': 'EUR', 'Japan': 'JPY', 'England': 'GBP', 'Australia': 'AUD', 'Canada': 'CAD', 'Switzerland': 'CHF', 'China': 'CNH', 'Hong Kong': 'HKD', 'New Zealand': 'NZD'}