Python

Python – How to merge two dict in Python ?

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.

But be careful you can only use this operation on Python 2, If you do the same operation on Python 3 you can get TypeError: unsupported operand type(s) for +: ‘dict_items’ and ‘dict_items’.
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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Python

How to access for loop index in Python

The built-in Python enumerate function is a better way to access the for loop index. How to access for loop index in Python: The builtin enumerate function available…

Ask a question or leave a comment