Last modified: Jun 02, 2023 By Alexander Williams

Merge Two Dictionaries with Same Keys in Python

In this tutorial, we'll see how to merge two dictionaries with the same keys. To merge two dictionaries with the same keys in Python, you can use the update() method.

Merging Using update() method

In Python, the update() method is used to update one dictionary with the key-value pairs from another or an iterable of key-value pairs. Let's use it to merge two dictionaries with the same keys.

def merge_dicts(dict1, dict2):
    merged_dict = dict1.copy()  # Create a copy of the first dictionary

    merged_dict.update(dict2)  # Merge the second dictionary into the first dictionary

    return merged_dict

# Example usage
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}

merged_dict = merge_dicts(dict1, dict2)
print(merged_dict)

Output:

{'a': 1, 'b': 4, 'c': 5, 'd': 6}

In this example, the function merge_dicts() takes two dictionaries as input (dict1 and dict2). It creates a copy of dict1 using the copy() method to ensure that the original dictionary is not modified. Then, it uses the update() method to merge the key-value pairs from dict2 into the merged_dict.

Conclusion:

Merging dictionaries with shared keys is a common task when working with data in Python. By utilizing the update() method, you can efficiently merge dictionaries and manage key-value pairs, allowing you to manipulate and organize your data effectively in Python.