Python - How To Change the Key in a Dictionary in Python

ID : 185

viewed : 173

Tags : PythonPython Dictionary

vote vote

100

This article introduces various methods to change the key in a dictionary in Python.

Assign New Key and in a Dictionary in Python

To change the key in a dictionary in Python, follow these steps.

  1. Assign a new key to the old key.
  2. Delete the old key.

Check the example below, which demonstrates these steps.

dict_ex[new_key] = dict_ex[old_key] del dict_ex[old_key] 

The following code illustrates this method.

dict_ex={ 1: 'January', 2:'Febuary', 3:'March' } print("Old dictionary-",dict_ex) dict_ex[2.1] = dict_ex[2] del dict_ex[2] print("New dictionary-",dict_ex) 

Here, we see that the key’s value 2 is replaced by the value 2.1. Please note how the updated key-value pair has moved to the end of the dictionary.

Output:

Old dictionary- {1: 'January', 2: 'Febuary', 3: 'March'} New dictionary- {1: 'January', 3: 'March', 2.1: 'Febuary'} 

Use the pop() Function in Python

To change the key in a dictionary in Python, refer to the following steps.

  • Pop the old key using the pop function. Follow this example.
    pop(old_key) 
  • Assign a new key to the popped old key. Follow this example.
    dict_ex[new_key] = dict_ex.pop(old_key) 

The example below illustrates this.

dict_ex={ 1: 'January', 2:'Febuary', 3:'March' } print("Old dictionary-",dict_ex) dict_ex[2.2] = dict_ex.pop(2) print("New dictionary-",dict_ex) 

Output:

Old dictionary- {1: 'January', 2: 'Febuary', 3: 'March'} New dictionary- {1: 'January', 3: 'March', 2.2: 'Febuary'} 

Here, we see that the key’s value 2 is replaced by the value 2.2. Please note how the updated key-value pair has moved to the end of the dictionary.

Traverse Through the Dictionary Using a for Loop and Change the Key in a Dictionary in Python

For this, you first take the target dictionary and another dictionary containing the new key value. After that, you eventually switch all the keys accordingly using a for loop.

dict_ex = { 1 : 'Jan', 2 : 'Feb', 3 : 'Mar' } print("Old dictionary-",dict_ex) new_key_assign = { 1 : 111, 2 : 2, 3 : 3 } print("New dictionary-") print(dict([(new_key_assign.get(key), value) for key, value in dict_ex.items()])) 

Here, we see that the key’s value 1 is replaced by the value 111. Please note how the updated key-value pair has been retained this time.

Output:

Old dictionary- {1: 'Jan', 2: 'Feb', 3: 'Mar'} New dictionary- {111: 'Jan', 2: 'Feb', 3: 'Mar'} 

Rebuild an Entirely New Instance in Python

In the Python 3.7+ dictionary, you can preserve the ordering. For this, rebuild an entirely new instance of the dictionary as follows.

dict_ex = { <old_key> : 'Jan', 2 : 'Feb', 3 : 'Mar' }  {<new_key> if k == <old_key> else k:v for k,v in dict_ex.items()} 

Here is an example that demonstrates this.

dict_ex = { 1 : 'Jan', 2 : 'Feb', 3 : 'Mar' }  print({"one" if k == 1 else k:v for k,v in dict_ex.items()}) 

Here, we see that the key’s value 1 is replaced by the value one. Please note how the updated key-value pair has been retained this time.

Output:

{'one': 'Jan', 2: 'Feb', 3: 'Mar'} 

Use the OrderedDict Class in Python

In the Python 3.7+ dictionary, you can preserve the ordering by using the OrderedDict along with a generator expression.

Note that you first need to import OrderedDict from collections. Then, use the OrderedDict class.

from collections import OrderedDict dict_ex = { <old_key> : 'Jan', 2 : 'Feb', 3 : 'Mar' } OrderedDict((<new_key> if k == 1 else k, v) for k, v in dict_ex.items()) 

Here’s an example you can follow.

from collections import OrderedDict dict_ex = { 1 : 'Jan', 2 : 'Feb', 3 : 'Mar' } OrderedDict(("one" if k == 1 else k, v) for k, v in dict_ex.items()) 

Here, we see that the key’s value 1 is replaced by the value one. Please note how the updated key-value pair has been retained this time.

Output:

OrderedDict([('one', 'Jan'), (2, 'Feb'), (3, 'Mar')]) 

Use the Pandas.DataFrame Function in Python

You can use Pandas to change a key in a dictionary in Python. Firstly, import the pandas library.

Then, use the DataFrame utility as follows.

import pandas as pd <old_dictionary> = { <old_value> : 'Jan', 2 : 'Feb', 3 : 'Mar' } <new_dictionary>= { <new_value> : 'Jan', 2 : 'Feb', 3 : 'Mar' } df=pd.DataFrame([<old_dictionary>, <new_dictionary>])  

Check this example program.

import pandas as pd dict_ex = { 1 : 'Jan', 2 : 'Feb', 3 : 'Mar' } print(dict_ex) new_dict_ex= { 11 : 'Jan', 2 : 'Feb', 3 : 'Mar' } df=pd.DataFrame([dict_ex, new_dict_ex]) print(new_dict_ex) 

Here, we see that the key’s value 1 is replaced by the value 11. Please note how the updated key-value pair has been retained this time.

Output:

{1: 'Jan', 2: 'Feb', 3: 'Mar'} {11: 'Jan', 2: 'Feb', 3: 'Mar'} 

  • Related HOW TO?