How to Rename Keys in Python Dictionaries?

DDD
Release: 2024-11-01 02:25:28
Original
706 people have browsed it

How to Rename Keys in Python Dictionaries?

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

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

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}
>>> {&quot;two&quot; if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}</code>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!