When working with dictionaries in Python, to rename a key, you can use the dictionary pop() function.
dictionary = {"apples":3, "bananas":4, "pears":5}
dictionary["watermelon"] = dictionary.pop("apples")
print(dictionary)
#Output:
{"bananas":4, "pears":5, "watermelon":3}
You can also use the del keyword to rename a key in a dictionary variable in Python.
dictionary = {"apples":3, "bananas":4, "pears":5}
dictionary["watermelon"] = dictionary["apples"]
del dictionary["apples"]
print(dictionary)
#Output:
{"bananas":4, "pears":5, "watermelon":3}
In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements to rename their values.
We can easily rename keys in a Python dictionary.
To rename a key in a Python dictionary, you can use the dictionary pop() function to pop a key/value pair from the dictionary and assign it to a new key.
Below shows you an example of how to rename a key in a Python dictionary.
dictionary = {"apples":3, "bananas":4, "pears":5}
dictionary["watermelon"] = dictionary.pop("apples")
print(dictionary)
#Output:
{"bananas":4, "pears":5, "watermelon":3}
Using del to Rename Key in Python Dictionary Variable
Another way you can rename a key is with the Python del keyword. In this case, you will create a new key and then delete the key you want to change in your dictionary variable.
Below shows you how to change a key using the Python del keyword.
dictionary = {"apples":3, "bananas":4, "pears":5}
dictionary["watermelon"] = dictionary["apples"]
del dictionary["apples"]
print(dictionary)
#Output:
{"bananas":4, "pears":5, "watermelon":3}
Replacing Values in Python Dictionary
If you are want to replace a value in a dictionary in Python, then you just need to access it with the key name and reassign it with the new value.
Below is an example in Python of how to reassign and replace a value in a dictionary.
dictionary = {"apples":3, "bananas":4, "pears":5}
dictionary["apples"] = 6
print(dictionary)
#Output:
{"apples":6, "bananas":4, "pears":5}
Hopefully this article has been useful for learning how to replace values in dictionaries using Python.