Merging Of Two Dictionaries

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:

# 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:

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

 


Copyright 2023 © pythontic.com