There are different ways to merge two dict in python. Let’s see how we can do this.
How to merge two dict in Python?
Python dictionary is a key, value pair data structure. This tutorial about how to merge the two dictionaries in python.
1. dict.copy()
Using dict.copy()
function we can merge the two dicts, if you are using Python 2 to < 3.4, then you can take advantage of dict.copy() function to merge two dictionaries.
def merge_dict(dic1, dic2):
copy = dic1.copy()
copy.update(dic2)
return copy
if __name__ == '__main__':
merged = merge_dict({'a': 1, 'b': 2}, {'c': 3})
print(merged)
Output:
{'a': 1, 'b': 2, 'c': 3}
2. Merge with single Expression:
New syntax has been added in Python 3.5
, to achieve this in a single expression. If you are using Python 3.5
, you can have a look at it.
def merge_dict2(dic1, dic2):
return {**dic1, **dic2}
if __name__ == '__main__':
merged = merge_dict2({'a': 1, 'b': 2}, {'c': 3})
print(merged)
Output:
{'a': 1, 'b': 2, 'c': 3}
3. Merge with + operator:
We can even merge two dictionaries by using +
operator in between them.
def merge_dict3(dic1, dic2):
return dict(dic1.items() + dic2.items())
if __name__ == '__main__':
merged = merge_dict3({'a': 1, 'b': 2}, {'c': 3})
print(merged)
Output:
{'a': 1, 'b': 2, 'c': 3}
4. Merge with a list of dict:
As per the above example, we can not use the +
operator to merge the two dict directly in Python 2
, but we can do it with two lists. This will work on both Python 2 and 3
.
def merge_dict4(dic1, dic2):
return dict(list(dic1.items()) + list(dic2.items()))
if __name__ == '__main__':
merged = merge_dict4({'a': 1, 'b': 2}, {'c': 3})
print(merged)
Output:
{'a': 1, 'b': 2, 'c': 3}
Done!
References:
Happy Learning 🙂