Change Dictionary Items
Dictionaries in Python are mutable, which means you can change existing values, add new key–value pairs, and update multiple items at once.
This topic explains all correct ways to change dictionary items, with examples and best practices.
Change Value Using Key
You can change the value of an existing key by assigning a new value.
python
student = {
"name": "Jayesh",
"age": 25,
"course": "Python"
}
student["age"] = 26
print(student)
Change Value Using update()
The
update() method can change one or more values.python
student.update({"age": 27})
print(student)
python
student.update({"course": "AWS", "city": "Pune"})
print(student)
Add New Item While Updating
If the key does not exist,
update() adds it.python
student.update({"salary": 50000})
print(student)
Change Dictionary Items Using Loop
python
scores = {"A": 80, "B": 70, "C": 60}
for key in scores:
scores[key] += 5
print(scores)
Change Nested Dictionary Items
python
students = {
"student1": {"name": "Amit", "age": 20},
"student2": {"name": "Riya", "age": 22}
}
students["student1"]["age"] = 21
print(students)
Change Value Safely Using get()
python
if student.get("age"):
student["age"] = 28
Change Keys (Indirect Way)
Dictionary keys cannot be changed directly.
You must remove and reinsert.
python
person = {"nam": "Amit", "age": 30}
person["name"] = person.pop("nam")
print(person)
Replace Entire Dictionary
python
student = {"name": "Jayesh"}
student = {"name": "Amit", "age": 25}
print(student)
Change Using Dictionary Comprehension
python
scores = {"A": 80, "B": 70}
scores = {k: v + 10 for k, v in scores.items()}
print(scores)
Common Mistakes
Using Index Instead of Key
python
# student[0] = "Test" # TypeError
Forgetting That Assignment Overwrites Value
python
student["age"] = 30
student["age"] = 35
Only the latest value remains.
Best Practices
- Use direct assignment for single updates
- Use
update()for bulk changes - Use loops for conditional updates
- Modify nested dictionaries carefully
- Avoid changing keys unless necessary
Summary
- Dictionary items can be changed using keys
update()modifies or adds items- Nested dictionaries require chained access
- Keys cannot be modified directly
- Dictionary comprehensions allow bulk updates
- Dictionaries are flexible and powerful