
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How can we merge two Python dictionaries?
In Python 3.5+, you can use the ** operator to unpack a dictionary and combine multiple dictionaries using the following syntax:
a = {'foo': 125} b = {'bar': "hello"} c = {**a, **b} print(c)
This will give the output:
{'foo': 125, 'bar': 'hello'}
This is not supported in older versions. You can however replace it using the following similar syntax:
a = {'foo': 125} b = {'bar': "hello"} c = dict(a, **b) print(c)
This will give the output:
{'foo': 125, 'bar': 'hello'}
Another thing you can do is using copy and update functions to merge the dictionaries. For example,
def merge_dicts(x, y): z = x.copy() # start with x's keys and values z.update(y) # modify z with y's keys and values return z a = {'foo': 125} b = {'bar': "hello"} c = merge_dicts(a, b) print(c)
This will give the output:
{'foo': 125, 'bar': 'hello'}
- Related Articles
- Python program to merge two Dictionaries
- How to merge two Python dictionaries in a single expression?
- How to merge multiple Python dictionaries?
- How do we compare two dictionaries in Python?
- C# program to merge two Dictionaries
- Swift Program to Merge two Dictionaries
- Python program to merge to dictionaries.
- How can we merge two JSON objects in Java?
- How can we merge two JSON arrays in Java?
- Python – Merge Dictionaries List with duplicate Keys
- How can I merge two MySQL tables?
- Python - Intersect two dictionaries through keys
- Python - Difference in keys of two dictionaries
- Python – Merge two Pandas DataFrame
- Program to find number of ways we can merge two lists such that ordering does not change in Python

Advertisements