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:
<code class="python">mydict[k_new] = mydict.pop(k_old)</code>
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:
<code class="python">{k_new if k == k_old else k: v for k, v in od.items()}</code>
This can be used to rename a key while preserving the order, such as renaming key 2 to 'two':
<code class="python">>>> 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}</code>
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.
The above is the detailed content of How to Rename Keys in Python Dictionaries?. For more information, please follow other related articles on the PHP Chinese website!