Home »
Python
Merge two dictionaries in a single expression in Python
Merging two dictionaries: Here, we are going learn how to merge two dictionaries in a single expression in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on October 22, 2019
Until version less than 3.4, in python, it was quite a task (no single line approach available) to merge two dictionaries in a single expression. For instance, in version less than 3.4 we had to do something similar (as below) to merge two dictionaries.
def merge(dict_1, dict_2):
z = dict_1.copy()
z.update(dict_2)
return z
if __name__ == "__main__":
dict_1 = {'x':1, 'y':2}
dict_2 = {'a':3, 'b':4}
merged_dict = merge(dict_1, dict_2)
print(merged_dict)
Output
{'x': 1, 'y': 2, 'a': 3, 'b': 4}
In the above example, (ref merge method), the dict_1 is shallow copied to a different variable called z, and the z is then updated with the values of dict_2, which results in the merging of two dictionaries.
Merge two dictionaries in a single line
With python 3.5+, the below approach is generally followed to merge two (or more) dictionaries.
if __name__ == "__main__":
dict_1 = {'x':1, 'y':2}
dict_2 = {'a':3, 'b':4}
merged_dict = {**dict_1, **dict_2}
print(merged_dict)
Output
{'x': 1, 'y': 2, 'a': 3, 'b': 4}
The above can be used to merge two or more dictionaries, like below,
if __name__ == "__main__":
dict_1 = {'x':1, 'y':2}
dict_2 = {'a':3, 'b':4}
dict_3 = {'p':5, 'q':6}
merged_dict = {**dict_1, **dict_2, **dict_3}
print(merged_dict)
However, since most of the organizations have not yet moved to the latest version of Python, the general approach followed is as mentioned in the initial example.