Python Update Dictionary Value by Key
Last Updated :
19 Jan, 2024
A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can modify them in place.
In this article, I have explained how to update the value of an existing Key Dictionary. You only need to reassign a new value to that key. Python dictionaries allow for this direct modification.
Python Update Dictionary Value by Key
Here, we are explaining methods that explain how to Update Dictionary Value by Key in Python those are following.
- Using The Square Brackets
- Using U
pdate()
Method
- Using a Conditional Statement
- Using S
etdefault
Method
Update Dictionary by Key Using The Square Brackets
In this example, I have created a dictionary student_info, and we updated the ‘grade’ key to the new value ‘A’ using the square bracket notation.
Python
student_info = { 'name' : 'Geek' , 'age' : 21 , 'grade' : 'B' }
student_info[ 'grade' ] = 'A'
print (student_info)
|
Output
{'grade': 'A', 'age': 21, 'name': 'Geek'}
Update Dictionary by Key Using Update()
Method
In this example, below code updates the ‘grade’ value in the student_info
dictionary to ‘A’ using the update()
Method and then its prints the updated dictionary.
Python3
student_info = { 'name' : 'Geek' , 'age' : 21 , 'grade' : 'B' }
student_info.update({ 'grade' : 'A' })
print (student_info)
|
Output
{'name': 'Geek', 'age': 21, 'grade': 'A'}
Update Dictionary by Key Using a Conditional Statement
In this example, below code checks if the key ‘grade’ is in the `student_info` dictionary and, if true, updates its value to ‘A’; then, it prints the updated dictionary `student_info`we used for these conditional statement .
Python3
student_info = { 'name' : 'Geek' , 'age' : 21 , 'grade' : 'B' }
if 'grade' in student_info:
student_info[ 'grade' ] = 'A'
print (student_info)
|
Output :
{'name': 'Geek', 'age': 21, 'grade': 'A'}
Update Dictionary by Key Using Setdefault
Method
In this example code uses the `setdefault()` method to update the ‘grade’ value to ‘A’ in the `student_info` dictionary if the key ‘grade’ is not already present, and then prints the updated dictionary.
Python3
student_info = { 'name' : 'Geek' , 'age' : 21 , 'grade' : 'B' }
student_info.setdefault( 'grade' , 'A' )
print (student_info)
|
Output :
{'name': 'Geek', 'age': 21, 'grade': 'A'}
Share your thoughts in the comments
Please Login to comment...