Update a Dictionary in Python

Updating a dictionary involves adding or modifying key-value pairs in an existing dictionary. In this blog post, we will explore different methods to update a dictionary in Python.

Method 1: Using the update() Method

# Method 1: Using the update() Method
my_dict = {"name": "John", "age": 30}
my_dict.update({"city": "New York", "country": "USA"})
print("Updated dictionary:", my_dict)

Output:

Updated dictionary: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’, ‘country’: ‘USA’}

Method 2: Using the assignment operator

# Method 2: Using the assignment operator
my_dict = {"name": "John", "age": 30}
my_dict["city"] = "New York"
my_dict["country"] = "USA"
print("Updated dictionary:", my_dict)

Output:

Updated dictionary: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’, ‘country’: ‘USA’}