Write a Python Program to Merge Two Dictionaries

Python Program to Merge Two Dictionaries

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn  Python programming concepts. You can learn Python language at your own speed and time. One can learn concepts of Python language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Python Program to Merge Two Dictionaries
Python Program to Merge Two Dictionaries

Write a Python Program to Merge Two Dictionaries

PROGRAM: Python Program to Merge Two Dictionaries

/* Python Program to Merge Two Dictionaries */

1: Using the | Operator

dict_1 = {1: ‘a’, 2: ‘b’}
dict_2 = {2: ‘c’, 4: ‘d’}

print(dict_1 | dict_2)

OUTPUT:-

{1: 'a', 2: 'c', 4: 'd'}

2: Using the ** Operator

dict_1 = {1: ‘a’, 2: ‘b’}
dict_2 = {2: ‘c’, 4: ‘d’}

print({**dict_1, **dict_2})

OUTPUT:-

{1: 'a', 2: 'c', 4: 'd'}

3: Using copy() and update()

dict_1 = {1: ‘a’, 2: ‘b’}
dict_2 = {2: ‘c’, 4: ‘d’}

dict_3 = dict_2.copy()
dict_3.update(dict_1)

print(dict_3)

OUTPUT:-

{2: 'b', 4: 'd', 1: 'a'}

Leave a Reply

Your email address will not be published. Required fields are marked *