For a regular dict, you can use:

mydict[k_new] = mydict.pop(k_old)

This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.

For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':

>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}

The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:

OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())

Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.

Answer from wim on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-change-the-name-of-a-key-in-dictionary
How to Change the name of a key in dictionary? - GeeksforGeeks
July 23, 2025 - def rename_key_nested(dictionary, old_key, new_key): 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) # Original nested dictionary nested_dict = { 'level1': { 'old_key': 'value', 'level2': { 'old_key': 'value2' } } } # Rename 'old_key' to 'new_key' in nested dictionary rename_key_nested(nested_dict, 'old_key', 'new_key') print(nested_dict) ... Changing the name of a key in a dictionary is a common task in Python programming.
Discussions

python - Change the name of a key in dictionary - Stack Overflow
How do I change the key of an entry in a Python dictionary? More on stackoverflow.com
🌐 stackoverflow.com
performance - Efficient renaming of dict keys from another dict's values - Python - Code Review Stack Exchange
The code works as desired, and prints the dictionary with renamed keys as shown below: {'ORDER_NUMBER': '6492', 'ShipToCompany': 'J.B Brawls', 'ShipToAddress1': '42 BAN ROAD', 'ShipToCity': 'Jimville', 'ShipToState': 'VA', 'ShipToZipcode': '42691'} My question is, is there any more efficient/more Pythonic ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 9, 2021
Why doesn't rename seem to work for me with these invalid key names in my dictionary?
PyDev console: starting. Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32 from collections import namedtuple def tuplify_rename(): data = {‘name’: ‘Bob’, ‘age’:44, ‘city’:‘rome’, ‘zip-code’: ‘10001’, ‘for’: ... More on discuss.python.org
🌐 discuss.python.org
4
0
June 20, 2025
Update key, Rename Key C# Dictionary
Experts, Is there a way to change the Key in C# Dictionary. Removing and Adding is not an option because I don`t have access to the Value in the scope. Dict[Key1, ValueX] should be the same as Dict[Key2, ValueX]. How do I rename/update Key1 to Key2? Is this even possible? More on experts-exchange.com
🌐 experts-exchange.com
February 23, 2010
🌐
Note.nkmk.me
note.nkmk.me › home › python
Change a Key Name in a Dictionary in Python | note.nkmk.me
August 21, 2023 - Merge multiple dictionaries and add items to a dictionary in Python · Since dict does not provide a method to directly rename a key, you need to add a new item with the new key and original value, then remove the old item.
🌐
GitHub
gist.github.com › JokerMartini › c3a38069020480727e5e
Python: Renames recursively every key in a dictionary to lowercase. · GitHub
def dict_rename_key(iterable, old_key, new_key): """ dict_rename_key method Args: iterable (dict): [description] old_key (string): [description] new_key (string): [description] Returns: dict: [description] Examples: >>> data = {'MIKE': 'test', 'JOHN': 'doe'} >>> data_modified = dict_rename_key(data, 'MIKE', 'mike') >>> assert 'mike' in data_modified """ if isinstance(iterable, dict): for key in list(iterable.keys()): if key == old_key: iterable[new_key] = dict_rename_key(iterable.pop(key), old_key, new_key) else: iterable[key] = dict_rename_key(iterable.pop(key), old_key, new_key) return iterable
🌐
W3Schools
w3schools.com › python › python_dictionaries_change.asp
Python - Change Dictionary Items
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else
Find elsewhere
🌐
Pybites Platform
pybitesplatform.com › bites › rename-keys
Rename keys
Some of the dictionary keys start with @ symbols and the Accounting Department will have none of this. Complete the rename_keys() function to remove the @ character from the beginning of the dictionary key names(Warning: Not all the dictionary ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-ways-to-change-keys-in-dictionary
Ways to change keys in dictionary - Python - GeeksforGeeks
May 13, 2025 - A new dictionary is created using dict(). This code replaces the key 'Amit' with 'Suraj' in a dictionary while keeping the other key-value pairs unchanged.
Top answer
1 of 2
19

I'd use a dict comprehension:

pretty_dict = {replacement_keys[k]: v for k, v in ugly_dict.items()}

This throws an error if replacement_keys (keyMapping) is missing any k. You might want to handle that with a default that falls back to the original key:

pretty_dict = {replacement_keys.get(k, k): v for k, v in ugly_dict.items()}

Time complexity is linear, assuming constant time dict lookups.

The main point of dicts is fast lookups, not iteration, so alarm bells should sound if you find yourself doing nested loops over multiple dicts.


Style suggestions:

  • Use snake_case rather than camelCase per PEP-8.
  • Generally avoid appending the type to every variable, users_count, source_string, names_list, translation_dict and so forth, although I assume this is for illustrative purposes here.
  • .keys() is superfluous as far as I know, but then again it doesn't hurt. You shouldn't need to loop over keys on a dict often.
2 of 2
2

The point of dictionaries is that lookup is fast, but you are not using that even though your keyMapping already is a dictionary. Let us look at your code.

prettyDict = {}
for mkey, mval in keyMapping.items():
    for ukey in uglyDict.keys():
        if mkey == ukey:
            prettyDict[mval] = uglyDict[mkey]

Even if uglyDict is small, you iterate over all element of the key mapping. This seems to be a bad starting point, so let us reverse the two loops.

prettyDict = {}
for ukey in uglyDict.keys():
    for mkey, mval in keyMapping.items():
        if mkey == ukey:
            prettyDict[mval] = uglyDict[mkey]

In the last line, mkey equals ukey, so we can change that to uglyDict[ukey], and of course you know how to avoid that lookup altogether:

prettyDict = {}
for ukey, uval in uglyDict.items():
    for mkey, mval in keyMapping.items():
        if mkey == ukey:
            prettyDict[mval] = uval

Let us now concentrate on the middle part:

    for mkey, mval in keyMapping.items():
        if mkey == ukey:

Here we look for the value of ukey in keyMapping, but surely that is what dictionaries are for and we don't have to iterate over all items to do so.

prettyDict = {}
for ukey, uval in uglyDict.items():
    if ukey in keyMapping:
        mval = keyMapping[ukey]
        prettyDict[mval] = uval

This is much better. From here, we can reformulate this using a dictionary comprehension like in ggorien's answer, if you prefer that.

prettyDict = {
    keyMapping[ukey]: uval
    for ukey, uval in uglyDict.items()
    if ukey in keyMapping
}

More importantly, you should decide how to handle the case that ukey is not in keyMapping. (Your example seems to have that got wrong with ORDER_NUMBER, btw.) If this would be a error, just omit the if ukey in keyMapping and handle the exception elsewhere. Or maybe you would like to keep the original key in that case:

prettyDict = {
    keyMapping.get(ukey, ukey): uval
    for ukey, uval in uglyDict.items()
}
🌐
Tutorjoes
tutorjoes.in › Python_example_programs › rename_key_dict_in_python
Write a Python program to Rename key of a dictionary
Next, the program adds two new key-value pairs to the dictionary. The first uses the new variable containing the value of ... student = { "Name": "Tara", "RollNo":130046, "Mark": 458, "Age":16, } print("Before Rename Key of a Dictionary :",student) student["Mark10"] = student.pop("Mark") student["RegNo"] = student.pop("RollNo") print("After Rename Key of a Dictionary :",student)
🌐
W3Schools
w3schools.com › python › gloss_python_change_dictionary_item.asp
Python Change Values in a Dictionary
Python Dictionaries Tutorial Dictionary Access Dictionary Items Loop Dictionary Items Check if Dictionary Item Exists Dictionary Length Add Dictionary Item Remove Dictionary Items Copy Dictionary Nested Dictionaries
🌐
Python.org
discuss.python.org › python help
Why doesn't rename seem to work for me with these invalid key names in my dictionary? - Python Help - Discussions on Python.org
June 20, 2025 - PyDev console: starting. Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32 from collections import namedtuple def tuplify_rename(): data = {‘name’: ‘Bob’, ‘age’:44, ‘city’:‘rome’, ‘zip-code’: ‘10001’, ‘for’: ‘reserved_word’} Person = namedtuple(‘Person’, [‘name’, ‘age’, ‘city’, ‘zip-code’, ‘for’], rename=True) return Person(**data) print(tuplify_rename()) Traceback (most recent call last): File “”, line 1, in File “”, line 4, in tuplify_...
🌐
YouTube
youtube.com › 1 minute python
How to Rename Dictionary Keys in Python - YouTube
How to Rename Dictionary Keys in Python
Published   April 4, 2024
Views   2
🌐
Python
docs.python.org › 3 › library › os.html
os — Miscellaneous operating system interfaces
Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary.
🌐
Experts Exchange
experts-exchange.com › questions › 25196858 › Update-key-Rename-Key-C-Dictionary.html
Solved: Update key, Rename Key C# Dictionary | Experts Exchange
February 23, 2010 - Djjaries is right, what I am suggesting is iterate through the dictionary by Linq querying the value. Which is bit expensive. Are you using the latest version of .NET and C# (i mean .net 3.5 or C# 3.0) ? If yes, as I mentioned above, you can give a try. ... I`m using 3.0. ... string key = string.Empty; foreach (DictionaryEntry de in Dict) { if(de.Value.Compare(ValueX)==0) { key = de.Key; } }
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-add-new-keys-to-a-dictionary
Add new keys to a dictionary in Python - GeeksforGeeks
July 11, 2025 - If a key already exists then its value is updated. We can use | operator to create a new dictionary by merging existing dictionaries or adding new keys and values.
🌐
Python Forum
python-forum.io › thread-29205.html
How do you replace a dictionary key with a new input?
August 22, 2020 - Good afternoon Python community, I am practicing my Python skills by working on a log-in/registration script that asks if you are currently registered. If Y for 'Yes', then it runs the user through a