How to combine two dictionaries in python using different methods
Max
Posted on March 5, 2023
Python Dictionary is a data structure that used to store elements in key-value pairs. Unlike python list values in the dictionary are retrieved or stored using the key. Dictionary is declared using the curly braces {} and the key value pair separated by : colon.
combine two dictionaries using python for loop
mydict1 = {
"car": 5,
"bus": 3,
"bike": 10
}
mydict2 = {
"cycle": 4,
"truck": 8,
"car": 6
}
for key in mydict2:
mydict1[key] = mydict2[key]
print("mydict1:", mydict1)
Output:
mydict1: {'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}
key car exists in both variable, we doing the merge operation if the key is not in the first mydict1 variable, it will add a new key value pair, if the key already exist in the dict it will update the value of the key.
This above example is a normal dictionaries merge example using loop, python have some inbuild features we can make use of it without doing for loop to combine dictionaries.
Dictionary Merge Operator
Using merge operator(|) it is easy to do the dictionary merge, its available from python 3.9
mydict1 = {
"car": 5,
"bus": 3,
"bike": 10
}
mydict2 = {
"cycle": 4,
"truck": 8,
"car": 6
}
print(mydict1 | mydict2)
Output:
{'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}
Merging Dictionaries Using ** Operator
This operator is used to pack and unpacking arguments, we can use the unpacking operator to merge two dictionaries
mydict1 = {
"car": 5,
"bus": 3,
"bike": 10
}
mydict2 = {
"cycle": 4,
"truck": 8,
"car": 6
}
print({**mydict1, **mydict2})
Output:
{'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}
Merging Dictionaries Using the update() Method
Python have a inbuild method called update which is used to merge or add one dictionary to another
mydict1 = {
"car": 5,
"bus": 3,
"bike": 10
}
mydict2 = {
"cycle": 4,
"truck": 8,
"car": 6
}
mydict1.update(mydict2)
print(mydict1)
Output:
{'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}
Using unpacking operator(**) and merge operator(|) only return the value where as here using the update method will update the values to the targeted variable.
Explore Other Related Articles
How to check if a key exists in a dictionary python
Python try exception tutorial
Python classes and objects tutorial
Python Recursion Function Tutorial
Python Lambda Function Tutorial
Python If, If-Else Statements Tutorial
Posted on March 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.