Dictionaries in Python are one of the most versatile and widely used data structures, storing data as key-value pairs for efficient retrieval and manipulation. However, there's no built-in method to directly rename a key. Instead, you need to create a new key-value pair and remove the old one.
In this guide, you'll learn multiple ways to rename a dictionary key in Python, from simple one-liners to reusable functions that handle nested dictionaries. Each method includes clear examples with outputs so you can pick the approach that best fits your use case.
Using pop() to Rename a Dictionary Key
The most straightforward and Pythonic way to rename a key is to use the pop() method. It retrieves and removes the old key's value in a single step, which you then assign to the new key.
my_dict = {'old_key': 'value'}
my_dict['new_key'] = my_dict.pop('old_key')
print(my_dict)Output:
{'new_key': 'value'}How it works:
my_dict.pop('old_key')retrieves the value associated with'old_key'and removes that entry from the dictionary.my_dict['new_key'] = ...creates a new entry with the desired key name and the retrieved value.
Using Dictionary Comprehension
Dictionary comprehension lets you create a new dictionary with the renamed key. This approach is especially useful when you want to preserve the original dictionary or rename keys conditionally.
my_dict = {'old_key': 'value', 'another_key': 'another_value'}
new_dict = {'new_key' if k == 'old_key' else k: v for k, v in my_dict.items()}
print(new_dict)Output:
{'new_key': 'value', 'another_key': 'another_value'}How it works:
The comprehension iterates over every key-value pair. When it encounters 'old_key', it substitutes 'new_key'; all other keys remain untouched.
Using the update() Method
The update() method adds new key-value pairs to a dictionary. Combined with pop(), it provides another clean way to rename a key.
my_dict = {'old_key': 'value', 'another_key': 'another_value'}
my_dict.update({'new_key': my_dict.pop('old_key')})
print(my_dict)Output:
{'another_key': 'another_value', 'new_key': 'value'}Note that the renamed key appears at the end of the dictionary since update() appends the new entry after removing the old one.
Renaming Multiple Keys at Once
When you need to rename several keys simultaneously, a mapping dictionary combined with a comprehension is the cleanest approach.
my_dict = {'first_name': 'Alice', 'last_name': 'Smith', 'dob': '1990-01-01'}
key_mapping = {
'first_name': 'given_name',
'last_name': 'surname',
'dob': 'date_of_birth'
}
renamed_dict = {key_mapping.get(k, k): v for k, v in my_dict.items()}
print(renamed_dict)Output:
{'given_name': 'Alice', 'surname': 'Smith', 'date_of_birth': '1990-01-01'}key_mapping.get(k, k) returns the new key name if a mapping exists; otherwise, it keeps the original key unchanged. This makes the approach safe for dictionaries that contain keys not present in the mapping.
Writing a Reusable Function
For better code readability and reusability, wrap the renaming logic in a dedicated function.
def rename_key(dictionary, old_key, new_key):
"""Rename a key in a dictionary in place. Does nothing if old_key is missing."""
if old_key in dictionary:
dictionary[new_key] = dictionary.pop(old_key)
my_dict = {'old_key': 'value', 'another_key': 'another_value'}
rename_key(my_dict, 'old_key', 'new_key')
print(my_dict)Output:
{'another_key': 'another_value', 'new_key': 'value'}The function modifies the dictionary in place and silently does nothing if the old key doesn't exist, making it safe to call without additional checks.
Handling Nested Dictionaries
Real-world data often contains nested structures. A recursive function can rename keys at every level of a nested dictionary.
def rename_key_nested(dictionary, old_key, new_key):
"""Recursively rename a key throughout a nested dictionary."""
for key in list(dictionary.keys()):
if isinstance(dictionary[key], dict):
rename_key_nested(dictionary[key], old_key, new_key)
if key == old_key:
dictionary[new_key] = dictionary.pop(old_key)
nested_dict = {
'level1': {
'old_key': 'value',
'level2': {
'old_key': 'value2'
}
}
}
rename_key_nested(nested_dict, 'old_key', 'new_key')
print(nested_dict)Output:
{'level1': {'level2': {'new_key': 'value2'}, 'new_key': 'value'}}Quick Comparison of Methods
| Method | In-Place | Preserves Order | Handles Nested | Best For |
|---|---|---|---|---|
pop() |
✅ | ❌ (moves to end) | ❌ | Simple, single key rename |
| Dictionary comprehension | ❌ (new dict) | ✅ | ❌ | Order-sensitive renames |
update() + pop() |
✅ | ❌ (moves to end) | ❌ | One-liner alternative |
| Key mapping + comprehension | ❌ (new dict) | ✅ | ❌ | Bulk renames |
| Custom function | ✅ | ❌ (moves to end) | ✅ (recursive) | Reusable, production code |
Conclusion
Python doesn't provide a built-in way to rename dictionary keys directly, but the language offers several flexible patterns to accomplish the task. For most situations, pop() combined with assignment is the simplest and most efficient solution. When key order matters, dictionary comprehension is the better choice. For complex or deeply nested data, a recursive helper function keeps your code clean and maintainable.
Choose the method that best matches your requirements, whether it's a quick one-liner in a script or a robust utility function in a production codebase.