Change Dictionary Items
Modifying Values
To update a dictionary, assign a new value to an existing key. If the key already exists, its value will be overwritten. This works for changing one or multiple keys.
Example
# Changing dictionary values
person = {"name": "John", "age": 30, "city": "New York"}
# Modify existing value
person["age"] = 31
print(person)
# Modify multiple values with update()
person.update({"age": 32, "city": "Boston"})
print(person)
Output
{'name': 'John', 'age': 31, 'city': 'New York'} {'name': 'John', 'age': 32, 'city': 'Boston'}
The update() Method
The update() method is a flexible way to change dictionary items. It accepts another dictionary or keyword arguments, updating existing keys and adding new ones if necessary.
Example
# Using update() method
person = {"name": "John", "age": 30}
# Update with another dictionary
person.update({"age": 31, "city": "New York"})
print(person)
# Update with keyword arguments
person.update(age=32, country="USA")
print(person)
Output
{'name': 'John', 'age': 31, 'city': 'New York'} {'name': 'John', 'age': 32, 'city': 'New York', 'country': 'USA'}
The setdefault() Method
The setdefault() method is used to retrieve the value of a key if it exists, or insert the key with a default value if it does not exist. This is useful when you want to ensure a key is present in a dictionary.
Example
# Using setdefault() method
person = {"name": "John", "age": 30}
# Key exists - returns value without changing
age = person.setdefault("age", 25)
print("Age:", age)
print(person)
# Key doesn't exist - adds key with default value
city = person.setdefault("city", "Unknown")
print("City:", city)
print(person)
Output
Age: 30 {'name': 'John', 'age': 30} City: Unknown {'name': 'John', 'age': 30, 'city': 'Unknown'}