Home > Article > Backend Development > How to Rename Dictionary Keys Without Reassignment or Iteration?
Renaming Dictionary Keys
Q: Is it possible to rename a dictionary key without reassignment or iteration?
A: For a Regular Dictionary:
Use this syntax to rename a key without affecting its value or order:
mydict[k_new] = mydict.pop(k_old)
For an Ordered Dictionary (Python 3.7 ):
To preserve ordering, recreate the dictionary with the updated key name:
{"two" if k == 2 else k:v for k,v in d.items()}
Note: Modifying the key itself is impractical as dictionary keys are usually immutable and havehable.
The above is the detailed content of How to Rename Dictionary Keys Without Reassignment or Iteration?. For more information, please follow other related articles on the PHP Chinese website!