Python
Dictionary
Key-Value
Programming
Data Structures

Change the name of a key in dictionary

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python dictionaries do not support renaming keys directly. To rename a key, you assign the value to the new key and delete the old key. The standard pattern is d[new_key] = d.pop(old_key), which moves the value in a single operation. For renaming multiple keys or transforming all keys, use a dictionary comprehension.

Basic Key Rename with pop()

python
1d = {"name": "Alice", "age": 30, "city": "NYC"}
2
3# Rename "name" to "full_name"
4d["full_name"] = d.pop("name")
5
6print(d)  # {"age": 30, "city": "NYC", "full_name": "Alice"}

dict.pop(key) removes the key and returns its value. Assigning it to a new key effectively renames it. If the old key does not exist, pop() raises KeyError — use a default to handle that:

python
# Safe rename — no error if key doesn't exist
d["full_name"] = d.pop("name", None)

Preserving Key Order

dict.pop() removes the old key's position and appends the new key at the end. To preserve insertion order:

python
1d = {"name": "Alice", "age": 30, "city": "NYC"}
2
3# Rebuild the dict with the renamed key in the same position
4d = {("full_name" if k == "name" else k): v for k, v in d.items()}
5
6print(d)  # {"full_name": "Alice", "age": 30, "city": "NYC"}

Renaming Multiple Keys

python
1d = {"first_name": "Alice", "last_name": "Smith", "dob": "1990-01-15"}
2
3# Mapping of old keys to new keys
4rename_map = {
5    "first_name": "firstName",
6    "last_name": "lastName",
7    "dob": "dateOfBirth"
8}
9
10# Rename using a comprehension
11d = {rename_map.get(k, k): v for k, v in d.items()}
12
13print(d)  # {"firstName": "Alice", "lastName": "Smith", "dateOfBirth": "1990-01-15"}

Keys not in rename_map are kept unchanged thanks to rename_map.get(k, k).

Renaming Keys in a List of Dictionaries

python
1records = [
2    {"first_name": "Alice", "last_name": "Smith"},
3    {"first_name": "Bob", "last_name": "Jones"},
4]
5
6rename_map = {"first_name": "firstName", "last_name": "lastName"}
7
8renamed = [
9    {rename_map.get(k, k): v for k, v in record.items()}
10    for record in records
11]
12
13print(renamed)
14# [{"firstName": "Alice", "lastName": "Smith"}, {"firstName": "Bob", "lastName": "Jones"}]

Case Conversion (snake_case to camelCase)

python
1import re
2
3def snake_to_camel(key):
4    parts = key.split("_")
5    return parts[0] + "".join(word.capitalize() for word in parts[1:])
6
7d = {"user_name": "alice", "email_address": "[email protected]", "is_active": True}
8d = {snake_to_camel(k): v for k, v in d.items()}
9
10print(d)  # {"userName": "alice", "emailAddress": "[email protected]", "isActive": True}

Nested Dictionary Key Rename

python
1def rename_keys(obj, rename_map):
2    if isinstance(obj, dict):
3        return {rename_map.get(k, k): rename_keys(v, rename_map) for k, v in obj.items()}
4    if isinstance(obj, list):
5        return [rename_keys(item, rename_map) for item in obj]
6    return obj
7
8data = {
9    "user_name": "Alice",
10    "address": {
11        "street_name": "Main St",
12        "zip_code": "10001"
13    },
14    "orders": [
15        {"order_id": 1, "total_price": 29.99}
16    ]
17}
18
19rename_map = {
20    "user_name": "userName",
21    "street_name": "streetName",
22    "zip_code": "zipCode",
23    "order_id": "orderId",
24    "total_price": "totalPrice"
25}
26
27result = rename_keys(data, rename_map)
28print(result)
29# {"userName": "Alice", "address": {"streetName": "Main St", "zipCode": "10001"}, ...}

In Other Languages

javascript
1// JavaScript — rename a key
2const obj = { name: "Alice", age: 30 };
3const { name: fullName, ...rest } = obj;
4const renamed = { fullName, ...rest };
5// { fullName: "Alice", age: 30 }
ruby
1# Ruby — rename a key in a hash
2h = { name: "Alice", age: 30 }
3h[:full_name] = h.delete(:name)
4# { age: 30, full_name: "Alice" }

Common Pitfalls

  • Modifying a dictionary while iterating: Calling d.pop() inside a for k in d loop raises RuntimeError: dictionary changed size during iteration. Collect keys to rename first, or use a dictionary comprehension to build a new dict.
  • Forgetting that pop() raises KeyError: If the old key does not exist, d.pop("missing_key") raises KeyError. Use d.pop("key", None) to provide a default value and avoid the error.
  • Losing key order with pop(): dict.pop() removes the key from its original position. The new key is appended at the end. If order matters, use a dictionary comprehension to rebuild the dict with the key in the correct position.
  • Overwriting an existing key: If new_key already exists in the dictionary, d[new_key] = d.pop(old_key) silently overwrites the existing value. Check for key existence first if this is undesirable.
  • Not handling nested dictionaries: Renaming keys in a flat dict does not affect nested dicts. For deeply nested data (like JSON API responses), use a recursive function that traverses all levels.

Summary

  • Use d[new_key] = d.pop(old_key) for a simple single-key rename
  • Use a dictionary comprehension {rename_map.get(k, k): v for k, v in d.items()} to rename multiple keys
  • Use d.pop(key, None) to avoid KeyError when the key might not exist
  • Dictionary comprehensions preserve key order; pop() moves the key to the end
  • For nested structures, write a recursive function that processes dicts and lists at all levels
  • In JavaScript, use destructuring with rest syntax for clean key renames

Course illustration
Course illustration

All Rights Reserved.