Key Rename in Dictionaries
Renaming a dictionary key can be achieved in several ways, depending on the type of dictionary and whether or not you want to maintain the key's position.
Regular Dict
For a regular dictionary, the key can be renamed using the following syntax:
mydict[k_new] = mydict.pop(k_old)
This operation moves the item to the end of the dictionary. If k_new already exists, its value will be overwritten.
OrderedDict (Python 3.7 )
In Python 3.7 , you can maintain the key's position in an OrderedDict by rebuilding the dictionary:
{k_new if k == k_old else k: v for k, v in od.items()}
This can be used to rename a key while preserving the order, such as renaming key 2 to 'two':
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}
Immutable Keys
Modifying the key itself, as suggested in the original question, is impractical because keys are usually hashable and therefore immutable. Modifying them would break the dictionary's integrity.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3