Aisha
asked

Expert
Kelish Rai answered
One simple way to merge two dictionaries without using update() is by using the unpacking (**) syntax.
For example:
A = {12: 'Kathmandu', 11: 'London', 3: 'Sydney'}
B = {10: 'New York', 2: 'Delhi'}
AB = {**A, **B}
print(AB)Output
{12: 'Kathmandu', 11: 'London', 3: 'Sydney', 10: 'New York', 2: 'Delhi'}Here,
The
{**A, **B}syntax unpacks the key-value pairs from both dictionariesAandBand combines them into a new dictionary,AB.This method will include all keys and values from both dictionaries.
Note: If there are overlapping keys, the value from the second dictionary (B) will overwrite the value from the first dictionary (A). For example,
A = {1: 'apple', 2: 'banana'}
B = {2: 'orange', 3: 'grape'}
AB = {**A, **B}
print(AB)Output
{1: 'apple', 2: 'orange', 3: 'grape'}Notice that key 2 has the value 'orange' from dictionary B, overwriting 'banana' from dictionary A.
In conclusion, the ** syntax is a very clean and Pythonic way to merge dictionaries, especially when you want to avoid using update().
Python
This question was asked as part of the Practice: Python Basics course.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer