Python | Ways to change keys in dictionary
Last Updated :
27 Apr, 2023
Given a dictionary, the task is to change the key based on the requirement. Let’s see different methods we can do this task in Python.
Example:
initial dictionary: {'nikhil': 1, 'manjeet': 10, 'Amit': 15}
final dictionary: {'nikhil': 1, 'manjeet': 10, 'Suraj': 15}
c: Amit name changed to Suraj.
Method 1: Rename a Key in a Python Dictionary using the naive method
Here, we used the native method to assign the old key value to the new one.
Python3
ini_dict = { 'nikhil' : 1 , 'vashu' : 5 ,
'manjeet' : 10 , 'akshat' : 15 }
print ( "initial 1st dictionary" , ini_dict)
ini_dict[ 'akash' ] = ini_dict[ 'akshat' ]
del ini_dict[ 'akshat' ]
print ( "final dictionary" , str (ini_dict))
|
Output
initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
final dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method 2: Rename a Key in a Python Dictionary using Python pop()
We use the pop method to change the key value name.
Python3
ini_dict = { 'nikhil' : 1 , 'vashu' : 5 ,
'manjeet' : 10 , 'akshat' : 15 }
print ( "initial 1st dictionary" , ini_dict)
ini_dict[ 'akash' ] = ini_dict.pop( 'akshat' )
print ( "final dictionary" , str (ini_dict))
|
Output
initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
final dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}
Method 3: Rename a Key in a Python Dictionary using Python zip()
Suppose we want to change all keys of the dictionary.
Python3
ini_dict = { 'nikhil' : 1 , 'vashu' : 5 ,
'manjeet' : 10 , 'akshat' : 15 }
ini_list = [ 'a' , 'b' , 'c' , 'd' ]
print ( "initial 1st dictionary" , ini_dict)
final_dict = dict ( zip (ini_list, list (ini_dict.values())))
print ( "final dictionary" , str (final_dict))
|
Output
initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
final dictionary {'a': 1, 'b': 5, 'c': 10, 'd': 15}
Creating a new dictionary and deleting the old one:
Approach:
Create a new empty dictionary new_dict.
Loop through each key-value pair in the original dictionary using the items() method.
If the current key is “Amit”, add a new key-value pair to new_dict with the key “Suraj” and the value from the original dictionary.
If the current key is not “Amit”, add the key-value pair from the original dictionary to new_dict.
Delete the old dictionary and rename new_dict to the original dictionary’s name.
Python3
my_dict = { 'nikhil' : 1 , 'manjeet' : 10 , 'Amit' : 15 }
new_dict = {}
for key, value in my_dict.items():
if key = = 'Amit' :
new_dict[ 'Suraj' ] = value
else :
new_dict[key] = value
del my_dict
my_dict = new_dict
print (my_dict)
|
Output
{'nikhil': 1, 'manjeet': 10, 'Suraj': 15}
Time Complexity: O(n)
Auxiliary Space: O(n)
Please Login to comment...