Change Keys of Dictionary in Python
In this tutorial, we will learn how to change keys of dictionary in Python.
Dictionary is a sequence of ( Key: Value ) pair.
Certainly, it is possible to change the keys in the Dictionary
Let’s just create a sample Dictionary.
Initial Dictionary :
sample = { 'bhanu' : 438 , 'surya' : 441 , 'jagan' : 427 } print (sample)
Output : {'bhanu': 438, 'surya': 441, 'jagan': 427}
Let’s see the various methods to change the keys in the dictionary.
Change Keys of Dictionary in Python
First method:
This approach is to simply create a new key with an existing value.
sample = { 'bhanu' : 438 , 'surya' : 441 , 'jagan' : 427 } print (sample) print() # Method 1 sample ['varshita'] = sample ['surya'] # new key "varshita" created with existing value del sample ['surya'] print (sample)
Output : {'bhanu': 438, 'jagan': 427, 'surya': 441} {'bhanu': 438, 'jagan': 427, 'varshita': 441}
Second method:
Using pop( ) built-in method of dictionary.
Before proceeding, let’s understand how it works.
sample = { 'bhanu' : 438 , 'surya' : 441 , 'jagan' : 427 } # Method 2 result = sample.pop('surya') # the return of this method is the value of sample['surya']. print (result) print (sample) # prints the dictionary excluding the key 'surya' as its removed.
Output : 441 {'bhanu': 438, 'jagan': 427}
Now, using this property to change the keys in the dictionary.
sample = { 'bhanu' : 438 , 'surya' : 441 , 'jagan' : 427 } # Method 2 sample ['sairam'] = sample.pop('surya') # adds key 'sairam' with a value of 441 [as 'surya ': 441] print (sample)
Output : {'sairam': 441, 'jagan': 427, 'bhanu': 438}
Concluding this, these are different ways to change the keys in a dictionary and can be helpful to do further operations.
Leave a Reply