How can you change the key of a dictionary in Python?
In Python, you can change the keys of a dictionary by following the steps below:
- Find the value corresponding to the key that needs to be modified.
- erase
- Create a new key-value pair with a new key, and assign the original value to the new key.
- Add the new key-value pair to the dictionary.
Here is a sample code:
my_dict = {'a': 1, 'b': 2, 'c': 3}
# 修改键'a'为'x'
value = my_dict.pop('a')
my_dict['x'] = value
print(my_dict) # 输出:{'b': 2, 'c': 3, 'x': 1}
In the example above, we start by removing the value associated with key ‘a’ using the pop method and assign it to the variable ‘value’. Next, we create a new key-value pair with the new key ‘x’ and assign the original value to the new key. Finally, we add the new key-value pair to the dictionary.