Python Change Dictionary Items
Modifying Dictionary Values
You can change the value of a specific key in a dictionary by:
- Assigning a new value using square brackets
- Using the
update()
method
Example 1: Change Item Using Square Brackets
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["year"] = 2020
print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Explanation: We updated the value of the key "year"
from 1964
to 2020
.
Example 2: Change Item Using update()
Method
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"model": "F-150"})
print(car)
Output:
{'brand': 'Ford', 'model': 'F-150', 'year': 2020}
Explanation: The update()
method changes the value of an existing key ("model"
) to "F-150"
.
Example 3: Add New Item with update()
(if not already present)
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "Blue"})
print(car)
Output:
{'brand': 'Ford', 'model': 'F-150', 'year': 2020, 'color': 'Blue'}
Explanation: If the key doesn’t exist, update()
will add a new key-value pair to the dictionary.
Square Brackets vs update()
Feature | Square Brackets | update() Method |
---|---|---|
Modify value | ✅ Yes | ✅ Yes |
Add new key-value | ✅ Yes | ✅ Yes |
Update multiple keys | ❌ One at a time | ✅ Multiple via dictionary |
Return value | ❌ No | ❌ No |
Example 4: Update Multiple Keys at Once
student = {
"name": "Alice",
"age": 22,
"course": "Math"
}
student.update({"age": 23, "course": "Python"})
print(student)
Output:
{'name': 'Alice', 'age': 23, 'course': 'Python'}
Explanation: Multiple keys ("age"
and "course"
) are updated at once using a single update()
call.
Example 5: Conditional Update
student = {
"name": "Alice",
"age": 22,
"course": "Math"
}
if "year" in car:
car["year"] = 2024
print(car)
Output:
{'brand': 'Ford', 'model': 'F-150', 'year': 2024, 'color': 'Blue'}
Explanation: This updates the value only if the key exists.
Conclusion
You can update dictionary values using either square brackets or the update()
method. update()
is more flexible when modifying multiple items at once.