Using the pop() or zip() function we can replace the dictionary key in Python. Even using the del keyword is possible.
Examples of replacing dictionary key in Python
A simple example changes the key of an entry in a Python dictionary.
Using basic and del keyword
Easily done in 2 steps:
dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}
# changing 'A' key
dic1['Z'] = dic1['A']
del dic1['A']
print(dic1)
Output:
Using pop() function
It will take one step only.
dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}
# changing 'A' key
dic1['Z'] = dic1.pop('A')
print(dic1)
Output: {‘B’: 5, ‘C’: 10, ‘D’: 15, ‘Z’: 1}
Using zip() function
Let’s replace all keys of the dictionary. But this will create a new dictionary.
dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}
kyes = ['X', 'Y', 'Z']
res = dict(zip(kyes, list(dic1.values())))
print(res)
Output: {‘X’: 1, ‘Y’: 5, ‘Z’: 10}
Do comment if you have any doubts or suggestions on this Python dictionary code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.