Python: How to merge two dictionaries (simple example)
To merge two dictionaries in Python, you can use the update() method.
This method adds the key-value pairs from one dictionary to another, overwriting any existing keys with the same name.
Here is an example of how to use the update() method to merge two dictionaries:
dict1 = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
dict2 = {
"key4": "value4",
"key5": "value5",
"key6": "value6"
}
dict1.update(dict2)
print(dict1)
This code creates two dictionaries, dict1 and dict2, and then uses the update() method to merge dict2 into dict1.
After the merge, dict1 will be equal to:
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5",
"key6": "value6"
}
Note that this method modifies dict1 in place, so you do not need to assign the result of update() to a new variable.
If you want to create a new dictionary that is the result of merging two other dictionaries, you can use the dict() constructor and the operator, like this:
dict1 = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
dict2 = {
"key4": "value4",
"key5": "value5",
"key6": "value6"
}
dict3 = dict(dict1, dict2)
print(dict3)
This code creates a new dictionary dict3 that is the result of merging dict1 and dict2. dict3 will be equal to:
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5",
"key6": "value6"
}
Note that this method does not modify the original dictionaries, so dict1 and dict2 will remain unchanged.

