Merge Dictionaries with Duplicate Keys in Python

Merging dictionaries with duplicate keys allows you to combine the key-value pairs from multiple dictionaries into a single dictionary. In this blog post, we will explore different methods to merge dictionaries with duplicate keys in Python.

Method 1: Using the update() method

# Method 1: Using the update() method
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "age": 35}
merged_dict = dict1.copy()
merged_dict.update(dict2)
print("Merged Dictionary:", merged_dict)

Output:

Merged Dictionary: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’}

Method 2: Using the double asterisk (**)

# Method 2: Using the double asterisk (**) operator
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "age": 35}
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)

Output:

Merged Dictionary: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’}