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

How to Rename Dictionary Keys Without Reassignment or Iteration?

Barbara Streisand
Release: 2024-11-02 00:50:02
Original
308 people have browsed it

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)
Copy after login

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()}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template