Update Values in a Dictionary in Python

Updating values in a dictionary allows you to modify or add new values to existing keys. In this blog post, we will explore different methods to update values in a dictionary in Python.

Method 1: Using the assignment operator

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

Output:

Updated dictionary: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’}

Method 2: Using the update() method

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

Output:

Updated dictionary: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’}