Python | Ways to change keys in dictionary
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} Explaination: 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
# inititialising dictionary ini_dict = { 'nikhil' : 1 , 'vashu' : 5 , 'manjeet' : 10 , 'akshat' : 15 } # printing initial json print ( "initial 1st dictionary" , ini_dict) # changing keys of dictionary ini_dict[ 'akash' ] = ini_dict[ 'akshat' ] del ini_dict[ 'akshat' ] # printing final result 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 2: Rename a Key in a Python Dictionary using Python pop()
We use the pop method to change the key value name.
Python3
# inititialising dictionary ini_dict = { 'nikhil' : 1 , 'vashu' : 5 , 'manjeet' : 10 , 'akshat' : 15 } # printing initial json print ( "initial 1st dictionary" , ini_dict) # changing keys of dictionary ini_dict[ 'akash' ] = ini_dict.pop( 'akshat' ) # printing final result 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
# inititialising dictionary ini_dict = { 'nikhil' : 1 , 'vashu' : 5 , 'manjeet' : 10 , 'akshat' : 15 } # initialising list ini_list = [ 'a' , 'b' , 'c' , 'd' ] # printing initial json print ( "initial 1st dictionary" , ini_dict) # changing keys of dictionary final_dict = dict ( zip (ini_list, list (ini_dict.values()))) # printing final result 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}
Please Login to comment...