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()
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:
Preserving Key Order
dict.pop() removes the old key's position and appends the new key at the end. To preserve insertion order:
Renaming Multiple Keys
Keys not in rename_map are kept unchanged thanks to rename_map.get(k, k).
Renaming Keys in a List of Dictionaries
Case Conversion (snake_case to camelCase)
Nested Dictionary Key Rename
In Other Languages
Common Pitfalls
- Modifying a dictionary while iterating: Calling
d.pop()inside afor k in dloop raisesRuntimeError: dictionary changed size during iteration. Collect keys to rename first, or use a dictionary comprehension to build a new dict. - Forgetting that
pop()raisesKeyError: If the old key does not exist,d.pop("missing_key")raisesKeyError. Used.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_keyalready 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 avoidKeyErrorwhen 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

