Check and Update Existing Key in Python Dictionary
Last Updated :
16 Jan, 2024
A dictionary in Python is an ordered 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 Dictionary is mutable, meaning you can modify them in place.
In this article, I have explained the process of updating existing keys in a dictionary in Python. To update an existing key in a dictionary, you’ll need to create a new key with the updated name and the same value as the old key and then delete the old key.
Update Existing Key in Dictionary Python
Here, are various ways to Update Existing Key in Dictionary Python. Here we are discussing some generally used methods to Update Existing key values key-value in Dictionary Python those are following.
Update Existing Key using Direct Assignment
In this example, the below code updates the dictionary by renaming the key ‘rank’ to ‘age’ while presenting the original value, and then removes the old key ‘rank’ and the updated dictionary is printed.
Python3
user = { 'name' : 'Geek' , 'rank' : 10 , 'city' : 'Geek Town' }
if 'rank' in user:
user[ 'age' ] = user[ 'rank' ]
del user[ 'rank' ]
print (user)
|
Output:
{'name': 'Geek', 'city': 'Geek Town', 'age': 10}
Update Existing Key using pop Method
In this example, a ‘user’ dictionary with 3 key-value pairs {‘name’: ‘Geek’, ‘rank’: 10, ‘city’: ‘Geek Town’} are present and I have updated the key ‘city’ to ‘town’ without changing the value.
Python
user = { 'name' : 'Geek' , 'rank' : 10 , 'city' : 'Geek Town' }
user[ 'town' ] = user.pop( 'city' )
print (user)
|
Output
{'town': 'Geek Town', 'name': 'Geek', 'rank': 10}
Check if a Key Exists in a Dictionary in Python
Using If Condition
In this example, we will first check if the old key ‘rank’ exists in the ‘user’ dictionary using the in operator. If it exists, we create a new key ‘age’ with the same value as the old key and then remove the old key using pop operation.
Python
user = { 'name' : 'Geek' , 'rank' : 10 , 'city' : 'Geek Town' }
if 'rank' in user:
user[ 'age' ] = user.pop( 'rank' )
print (user)
|
Output
{'city': 'Geek Town', 'age': 10, 'name': 'Geek'}
Using Try-Except Block
In this example , below code attempts to update the ‘age’ key in the dictionary by replacing the ‘rank’ key using the try-except block to handle the case where ‘rank’ key doesn’t exist.
Python3
user = { 'name' : 'Geek' , 'rank' : 10 , 'city' : 'Geek Town' }
try :
user[ 'age' ] = user.pop( 'rank' )
except KeyError:
pass
print (user)
|
Output :
{'name': 'Geek', 'city': 'Geek Town', 'age': 10}
Share your thoughts in the comments
Please Login to comment...