dictionary
key renaming
Python
programming
data manipulation

Rename a dictionary key

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Python dictionaries do not have a built-in “rename key” operation because a key is part of the hash-table identity. In practice, renaming means creating the new key and removing the old one. The best approach depends on whether you are changing one key, many keys, or nested data structures.

Rename One Key with pop

The most common pattern is to copy the value to a new key and remove the old one in one expression.

python
1user = {
2    "name": "Ava",
3    "email": "[email protected]",
4}
5
6user["contact"] = user.pop("email")
7print(user)

pop("email") returns the old value and removes the key from the dictionary. This is the cleanest one-key rename when you know the source key exists.

Handle Missing Keys Safely

If the old key may not be present, check first or provide a default. This prevents unexpected KeyError.

python
1user = {"name": "Ava"}
2
3if "email" in user:
4    user["contact"] = user.pop("email")
5
6print(user)

If you want a single expression and can tolerate a sentinel default:

python
value = user.pop("email", None)
if value is not None:
    user["contact"] = value

Be careful if None is also a valid real value in your data.

Renaming Multiple Keys at Once

For more than one rename, a new dictionary is often clearer than mutating in place repeatedly.

python
1record = {
2    "first_name": "Ava",
3    "last_name": "Stone",
4    "email": "[email protected]",
5}
6
7rename_map = {
8    "first_name": "firstName",
9    "last_name": "lastName",
10}
11
12renamed = {
13    rename_map.get(key, key): value
14    for key, value in record.items()
15}
16
17print(renamed)

This pattern scales well for schema transformations and API adaptation.

Preserve Order and Intent

Modern Python preserves insertion order in dictionaries, so renaming can subtly affect output order depending on how you do it. If order matters, a dictionary comprehension or ordered reconstruction is often easier to reason about than repeated mutation.

For example, user["contact"] = user.pop("email") moves the renamed key to the end. If that matters for output or tests, rebuild the dictionary in the desired order instead of mutating in place.

Renaming Keys in Nested Structures

Real data often contains nested dictionaries and lists. In those cases, write a helper that traverses recursively.

python
1def rename_keys(obj, rename_map):
2    if isinstance(obj, dict):
3        return {
4            rename_map.get(key, key): rename_keys(value, rename_map)
5            for key, value in obj.items()
6        }
7    if isinstance(obj, list):
8        return [rename_keys(item, rename_map) for item in obj]
9    return obj
10
11
12data = {
13    "user_name": "ava",
14    "profile": {
15        "user_email": "[email protected]"
16    },
17    "tags": [
18        {"user_email": "[email protected]"},
19        {"user_email": "[email protected]"},
20    ],
21}
22
23mapping = {
24    "user_name": "username",
25    "user_email": "email",
26}
27
28print(rename_keys(data, mapping))

This is useful when transforming JSON-like payloads between internal and external schemas.

When Not to Rename In Place

If other code still expects the old key, in-place renaming can introduce bugs that are hard to trace. In larger systems, prefer creating a transformed dictionary at boundaries instead of mutating shared input objects. This is especially important in request handlers, serializers, and data-cleaning pipelines.

Common Pitfalls

  • Using pop without handling missing keys.
  • Renaming in place when other code still depends on the original key.
  • Forgetting that in-place rename can change dictionary insertion order.
  • Mutating nested data manually in many places instead of using one helper.
  • Reusing one rename strategy when a clean rebuilt dictionary would be clearer.

Summary

  • Python renames dictionary keys by creating a new key and removing the old one.
  • For one key, new_key = d.pop(old_key) is the usual pattern.
  • For multiple renames, rebuilding the dictionary is often cleaner.
  • Use recursive helpers for nested JSON-like structures.
  • Prefer transformation at system boundaries over mutating shared dictionaries in place.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.