Python: How to Modify a Dictionary Key
In this article
Python dictionaries do not allow you to rename a key in place. The only reliable way to change a key is to create a new key with the desired name, assign it the existing value, and then delete the old key. For example, d['new'] = d.pop('old') does both steps in one line. This guide walks through that pattern, the safe ways to apply it to one key or many, and the mistakes that cause lost data or runtime errors.
What You'll Need
- Python 3 installed (any recent 3.x version works; the syntax shown here is standard).
- A text editor or IDE, or an interactive Python shell.
- A dictionary you want to change, either defined in your script or loaded from a file or API.
- Basic familiarity with dictionary syntax: curly braces, colons, and square-bracket access.
Step-by-Step
- Confirm the old key exists. Before renaming, check membership with
if 'old_key' in my_dict:. If the key is missing,popwithout a default raisesKeyError, so this guard prevents a crash. If you want a silent no-op when the key is absent, usemy_dict.pop('old_key', None)instead. - Decide the new key name. Keys must be hashable: strings, numbers, tuples of hashables. Lists and other dictionaries cannot be keys. Make sure the new name does not already exist in the dictionary, or you will overwrite that entry's value.
- Rename a single key with pop and assignment. The shortest correct pattern is:
my_dict['new_key'] = my_dict.pop('old_key')popremoves the old entry and returns its value, and the assignment stores that value under the new key. The insertion order of the renamed key moves to the end of the dictionary, which matters if you rely on ordering. - Preserve position if order matters. Python 3.7 and later keep insertion order. To keep the renamed key in its original slot, rebuild the dictionary:
my_dict = {('new_key' if k == 'old_key' else k): v for k, v in my_dict.items()}
This creates a new dictionary, so any other references to the original object will not see the change. - Rename several keys at once. Define a mapping of old names to new names and apply it in a loop or comprehension:
renames = {'old1': 'new1', 'old2': 'new2'}my_dict = {renames.get(k, k): v for k, v in my_dict.items()}
Usingget(k, k)leaves keys that are not in the mapping untouched. - Handle collisions deliberately. If a new key already exists, the comprehension above will let the later value win silently. Check first with
if 'new_key' in my_dict:and decide whether to skip, merge, or raise an error. Never assume the rename succeeded without verifying. - Verify the result. Print the dictionary or check
'new_key' in my_dict and 'old_key' not in my_dict. Also confirm the value is unchanged and that no other keys were affected. - Update any code that reads the old key. Renaming a key breaks every lookup, loop, or serialization that still uses the old name. Search your project for the old string before you commit the change.
Common Mistakes
- Assigning before deleting. Writing
my_dict['new_key'] = my_dict['old_key']without removing the old key leaves both entries in the dictionary. Always delete the old key, usually withpop. - Using
delbefore saving the value.del my_dict['old_key']discards the value permanently. Capture it first or usepop. - Assuming the key object itself changes. Strings are immutable; you cannot alter a key in place. A rename is always a remove-and-add operation.
- Mutating a dictionary while iterating over it. Changing keys inside a
for k in my_dict:loop raisesRuntimeError: dictionary changed size during iteration. Build a new dictionary or iterate over a copy withlist(my_dict.items()). - Forgetting that
popraises on missing keys. Without a default, a missing key stops the script. PassNoneor check membership first. - Overwriting an existing key. If the target name is already present, the assignment silently replaces its value. Check for collisions.
Tips
- Use
popwith a default when the key may or may not exist:value = my_dict.pop('old_key', None). - Write a small helper function such as
def rename_key(d, old, new): d[new] = d.pop(old)to keep the pattern consistent across a codebase. - If you rename keys often, consider whether a different data structure, such as a list of records or a class, would model the data better.
- Remember that renaming changes insertion order. If downstream code depends on order, rebuild the dictionary with a comprehension instead of pop-and-assign.
- When loading dictionaries from JSON, keys are always strings. Convert numeric keys explicitly if you need them as integers.
- Keep a copy of the original dictionary during development so you can compare before and after.
Troubleshooting
KeyError on the old key. The key is not present, possibly because of a typo, a different case, or a leading or trailing space. Print list(my_dict.keys()) to see the exact names.
The old key is still there. You assigned the new key but never removed the old one. Use pop or del after saving the value.
The new key overwrote existing data. The target name already existed. Restore from a backup or re-run the logic with a collision check.
RuntimeError during iteration. You modified the dictionary inside a loop. Iterate over a copy or build a new dictionary with a comprehension.
Other references do not see the change. Comprehensions and dict() create a new object. If other parts of the program hold a reference to the original, either mutate it in place with pop-and-assign or update every reference.
Order changed unexpectedly. Pop-and-assign moves the key to the end. Rebuild the dictionary to preserve position.
Frequently Asked Questions
Can I rename a dictionary key in place?
No. Python has no rename operation for dictionary keys. You must add the new key with the existing value and delete the old key, typically with my_dict['new'] = my_dict.pop('old').
What happens if the new key already exists?
The assignment overwrites the existing value for that key without warning. Check membership first if collisions are possible.
Does renaming a key change its position?
Yes, when you use pop-and-assign. The renamed key is inserted at the end. Rebuild the dictionary with a comprehension to keep the original order.
How do I rename multiple keys at once?
Use a mapping of old names to new names and a dictionary comprehension: {renames.get(k, k): v for k, v in my_dict.items()}. This leaves unmapped keys unchanged.
Why do I get a KeyError when renaming?
The old key is not in the dictionary, often due to a typo or case difference. Check with in or pass a default to pop.
Can I change a key while looping over the dictionary?
Not directly. Modifying the dictionary during iteration raises a RuntimeError. Iterate over a copy or build a new dictionary instead.