Sometimes, we want to rename a dictionary key with Python.
In this article, we’ll look at how to rename a dictionary key with Python.
How to rename a dictionary key with Python?
To rename a dictionary key with Python, we can use the dictionary’s pop
method.
For instance, we write:
d = {0: 0, 1: 1, 2: 2, 3: 3}
k_old = 0
k_new = 4
d[k_new] = d.pop(k_old)
print(d)
We have the dictionary d
, and we want to change the key of the first entry from 0 to 4.
To do this, we call d.pop
with k_old
to remove the the entry with key 0.
And then we set the entry with key k_new
to the dictionary entry value returned by pop
, which is the value 0.
Therefore, d
is {1: 1, 2: 2, 3: 3, 4: 0}
according to the print
output.
Conclusion
To rename a dictionary key with Python, we can use the dictionary’s pop
method.