Replace values
To replace values in a dictionary, you can use the following methods:
1. Direct assignment:
Python
my_dict = {"name": "Alice", "age": 30}
my_dict["age"] = 31
print(my_dict) # Output: {'name': 'Alice', 'age': 31}
2. update() method:
Python
my_dict = {"name": "Alice", "age": 30}
my_dict.update({"age": 31})
print(my_dict) # Output: {'name': 'Alice', 'age': 31}
Key points:
- Both methods directly modify the existing dictionary.
- The update() method can be used to replace multiple values at once.
- If the key doesn't exist, using direct assignment will create a new key-value pair, while update() will overwrite the existing value.
Example:
Python
person = {"name": "John", "age": 35, "city": "New York"}
# Replace the value for "age"
person["age"] = 32
# Replace multiple values using update()
person.update({"city": "Los Angeles", "occupation": "Engineer"})
print(person) # Output: {'name': 'John', 'age': 32, 'city': 'Los Angeles', 'occupation': 'Engineer'}
By understanding these methods, you can effectively replace values in dictionaries to update your data.