In this post we will be creating a Python script that will rename a dictionary key. Data in dictionaries in stored in key and value pairs, whereby each item will consist of a key and a value.
See below our dictionary for this example. Here our keys are a set of letters and the values are a sequence of numbers.
dictionary={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
See the snippet of Python code below where we rename the dictionary key containing the letter ‘a’ to the letter ‘x’. We start by creating a new dictionary item and give it the key ‘x’ and its value the same as ‘a’. We then delete the ‘a’ key and print the dictionary to output.
dictionary['x'] = dictionary['a']
del dictionary['a']
print(dictionary)
The above would return the following.
{'b': 2, 'c': 3, 'd': 4, 'e': 5, 'x': 1}
>>>
Take a look at some of our other content around the Python programming language by clicking here.