Instagram
youtube
Facebook
Twitter

Python Program to Rename a Key in a Dictionary

A Python Program to Rename a Key in a Dictionary?

Code Explanation:

Original Dictionary:
A dictionary named my_dict is created with keys: 'name', 'age', and 'city'.

Renaming Key:
The key 'city' is renamed to 'location' by using pop() to remove 'city' and assigning its value to 'location'.

Key Replacement:
my_dict["location"] = my_dict.pop("city") does the rename in a single line by removing the old key and creating a new one with the same value.

Updated Dictionary:
After the change, the dictionary has keys 'name', 'age', and 'location'.

Output Display:
The updated dictionary is printed with the renamed key.

 

Program:

my_dict = {

    "name": "Alice",

    "age": 25,

    "city": "London"

}

my_dict["location"] = my_dict.pop("city")

print(my_dict)