Ways to change keys in dictionary - Python
Last Updated :
13 May, 2025
Improve
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:
d = {'nikhil': 1, 'manjeet': 10, 'Amit': 15}
val = d.pop('Amit')
d['Suraj'] = val
print(d)
Output
{'nikhil': 1, 'manjeet': 10, 'Suraj': 15}
Explanation:
- The pop('Amit') method removes the key 'Amit' and returns its value.
- Then, we assign this value to the new key 'Suraj'.
- This way, the key 'Amit' is replaced by 'Suraj' in the dictionary.
Using the naive method
Here, we used the native method to assign the old key value to the new one.
d = {'nikhil': 1, 'vashu': 5,'manjeet': 10, 'akshat': 15}
print(d)
d['akash'] = d['akshat']
del d['akshat']
print(str(d))
Output
{'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15} {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}
Explanation:
- A new key 'akash' is added with the value of 'akshat'.
- The key 'akshat' is then deleted.
- This method modifies the dictionary in-place.
Using Python pop()
The pop() method removes a key and its corresponding value, which can then be reassigned to a new key.
d = {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
print(d)
d['akash'] = d.pop('akshat')
print(str(d))
Output
{'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15} {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}
Explanation:
- pop('akshat') removes the key 'akshat' and returns its value.
- This value is then assigned to the new key 'akash'.
Using Python zip()
The zip() function combines two lists, allowing you to pair new keys with the existing values in the dictionary.
d1 = {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
a = ['a', 'b', 'c', 'd']
print(d1)
d2 = dict(zip(a, list(d1.values())))
print(str(d2))
Output
{'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15} {'a': 1, 'b': 5, 'c': 10, 'd': 15}
Explanation:
- zip(ini_list, list(ini_dict.values())) pairs the new keys from ini_list with the values from ini_dict.
- A new dictionary is created using dict().
Creating a new dictionary and deleting the old one
This code replaces the key 'Amit' with 'Suraj' in a dictionary while keeping the other key-value pairs unchanged.
d1 = {'nikhil': 1, 'manjeet': 10, 'Amit': 15}
d2 = {}
for key, val in d1.items():
if key == 'Amit':
d2['Suraj'] = val
else:
d2[key] = val
del d1
d1 = d2
print(d1)
Output
{'nikhil': 1, 'manjeet': 10, 'Suraj': 15}
Explanation:
- The loop iterates through each key-value pair.
- The key 'Amit' is replaced with 'Suraj'.
- The original dictionary my_dict is deleted and replaced by new_dict.