How can i merge two dictionaries into a single expression in Python?
I want to merge two Python dictionaries into one single expression which returns the two dictionaries after merged. I'm using update method but it modifies the first dictionary instead of creating a new merged dictionary. Any suggestions?
d1 = { "A": 1, "B": 2, "C": 3 }
d2 = { "C": 4, "D": 5 }
d3 = d1.update(d2)
print(d3) # results none
print(d1) # prints {'A': 1, 'B': 2, 'C': 4, 'D': 5}
1 Answer
5 years ago by Jahaan
You can do it in below ways:
1. Using user-defined function
def merge_dict(dict1, dict2):
dict3 = dict1.copy()
dict3.update(dict2)
return dict3
d1 = { "A": 1, "B": 2, "C": 3 }
d2 = { "C": 4, "D": 5 }
print(merge_dict(d1,d2)) # prints {'A': 1, 'B': 2, 'C': 4, 'D': 5}
print(d1) # prints {'A': 1, 'B': 2, 'C': 3}
print(d2) # prints {'C': 4, 'D': 5}
2. Using **
d1 = { "A": 1, "B": 2, "C": 3 }
d2 = { "C": 4, "D": 5 }
d3 = {**d1, **d2}
print(d3) # prints {'A': 1, 'B': 2, 'C': 4, 'D': 5}
print(d1) # prints {'A': 1, 'B': 2, 'C': 3}
Note:
You can use + operator if you are still using python2.7
5 years ago by Divya