How to Add Two Dictionaries in Python
To add two dictionaries in Python, you can use two different methods.
The following examples show how to add two dictionaries using different methods in Python.
Using ** Operator
We can use the ** operator to add two dictionaries in Python.
Suppose we have the following dictionaries:
# Create dictionaries
dict1 = {'a': 100, 'b': 200}
dict2 = {'c': 300, 'd': 400}
# Add both dictionaries
dictionary = {**dict1, **dict2}
# Show updated dictionary
print("Updated dictionary:", dictionary)
Output: 👇️
Updated dictionary: {'a': 100, 'b': 200, 'c': 300, 'd': 400}
In this example, we use the ** operator to combine dict1 and dict2 into a new dictionary dictionary.
Using update() Function
We can use the update() function to add two dictionaries in Python.
Suppose we have the same dictionaries as above.
We can use the following code to add dict2 to dict1:
# Add both dictionaries
dict1.update(dict2)
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {'a': 100, 'b': 200, 'c': 300, 'd': 400}
In this example, we use the update() function to combine dict1 and dict2 into dict1.