Home  >  Article  >  Backend Development  >  How to Rename Dictionary Keys Without Reassignment or Iteration?

How to Rename Dictionary Keys Without Reassignment or Iteration?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 00:50:02190browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn