Merging dictionaries 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 two dictionaries in Python.
Method 1: Using the update() Method
# Method 1: Using the update() Method dict1 = {"name": "John", "age": 30} dict2 = {"city": "New York", "country": "USA"} dict1.update(dict2) print("Merged dictionary:", dict1)
Output:
Merged dictionary: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’, ‘country’: ‘USA’}
Method 2: Using the Double Asterisk (**) Operator
# Method 2: Using the Double Asterisk (**) Operator dict1 = {"name": "John", "age": 30} dict2 = {"city": "New York", "country": "USA"} merged_dict = {**dict1, **dict2} print("Merged dictionary:", merged_dict)
Output:
Merged dictionary: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’, ‘country’: ‘USA’}