python
Merge two or multiple dictionaries in Python
April 4, 2023
There are several ways to merge or concatenate two or more dictionaries in python. In this post, We will explain the methods and techniques to join two or more dictionaries in Python.
Using the merge() method (Python 3.9+):
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = dict1 | dict2
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using the update() method:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using the ** operator:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using the chain() method from the itertools module:
from itertools import chain
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = dict(chain(dict1.items(), dict2.items()))
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Was this helpful?
Similar Posts
- Merge two or multiple DataFrames in Pandas
- Check if two dictionaries are equal in Python
- Python collection - Dictionaries in python
- Join two or multiple lists in Python
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary
- Get all values by key name from a list of dictionaries Python
- Convert pandas DataFrame to List of dictionaries python