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

How to change the name of a key in a dictionary, ideally without deleting it?
Removing the old and adding new key-value pair is the only option. And what do you mean by "I don't really want to have to keep updating it"? If value1 is passed by value, you'll have to update it anyway and if it's passed by reference, changing the key doesn't matter because your new key will point to the same object. More on reddit.com
🌐 r/godot
8
2
November 20, 2021
performance - Efficient renaming of dict keys from another dict's values - Python - Code Review Stack Exchange
I have a dictionary in Python (uglyDict) that has some really un-cool key names. I would like to rename them based on values from another dictionary (keyMapping). Here's an example of the dictionar... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 9, 2021
How can I rename multiple files according to a dictionary? (possibly using os.rename)
Please edit your post to format your code for reddit or use a site like github or pastebin. Your code is hard to read and test otherwise. You don't need to loop over the current files. Just use a try block or the os.path.exists function to see if the file exists. # WARNING: this has the potential to permanently destroy data!! # it will not warn you before overwriting and it will not be in the recycle bin def rename_files(): for key, value in dict_.items(): if os.path.exisits(key): os.rename(key,value) More on reddit.com
🌐 r/learnpython
3
1
January 1, 2021
Rename dictionary keys/values in python - Stack Overflow
And after seeing that, I actually ... so much! Python is a beast, but I'm trying to ride it anyways. :) - as an aside - As a beginner to python, I love dictionaries, but they are the thing that I've needed the most help with.... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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
🌐
YouTube
youtube.com › brandonslockey
How to rename dictionary keys in python - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new featuresNFL Sunday Ticket · © 2024 Google LLC
Published   November 7, 2020
Views   3K
🌐
YouTube
youtube.com › watch
PYTHON : Rename a dictionary key - YouTube
PYTHON : Rename a dictionary key [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : Rename a dictionary key Note: The inf...
Published   December 9, 2021
Find elsewhere
🌐
Data Science Parichay
datascienceparichay.com › home › blog › rename a key in a python dictionary
Rename a Key in a Python Dictionary - Data Science Parichay
February 19, 2022 - To rename a Python dictionary key, use the dictionary pop() function to remove the old key from the dictionary and return its value. And then add the new key with the same value.
🌐
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)
🌐
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
🌐
Appdividend
appdividend.com › how-to-change-the-name-of-a-key-in-python-dictionary
How to Change the Name of a Key in Python Dictionary
December 12, 2025 - The most Pythonic and efficient way to change the name of a single key of a dictionary is to use the dict.pop() method. The pop() method removes a key and captures its value, then assigns that value to the new key.
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()
}
🌐
Medium
medium.com › @scriptopia › python-dictionaries-rename-dictionary-key-3502fbeba8f9
Python Dictionaries — Rename dictionary key - Scriptopia - Medium
December 17, 2022 - Here we are creating a Python script that will rename a dictionary key. Dictionaries provide us with a means of storing multiple items in…
🌐
CodeRivers
coderivers.org › blog › python-rename-dictionary-key
Renaming Dictionary Keys in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - Updating Related Code: If the dictionary is used in other parts of the code, make sure to update any references to the old key to the new key. This ensures the code continues to work as expected. Use Descriptive Variable Names: When renaming keys, use descriptive names for the new keys.
🌐
YouTube
youtube.com › codeflare
python dict rename key - YouTube
Download this code from https://codegive.com Title: Renaming Keys in a Python Dictionary: A Step-by-Step TutorialIntroduction:In Python, dictionaries are wid...
Published   December 20, 2023
Views   1
🌐
Reddit
reddit.com › r/learnpython › how can i rename multiple files according to a dictionary? (possibly using os.rename)
r/learnpython on Reddit: How can I rename multiple files according to a dictionary? (possibly using os.rename)
January 1, 2021 -

So I've created a dictionary with key: "current_filename" and value:"new_filename"

I want to create a function that automatically renames 10,000 of files according to the dictionary.

I'm having an issue setting up a proper 'for loops'.

Below is what I have so far.

def get_values():
    for count, filename in enumerate(os.listdir(path_)):
    # get new name that matches old name
    key_file = os.listdir(path_)[count]
    for key, value in dict_.items():
        if key_file == key:
        os.rename(key_file,value)
        continue

Your help is greatly appreciated!

🌐
w3tutorials
w3tutorials.net › blog › renaming-the-keys-of-a-dictionary
How to Rename Dictionary Keys in Python: A Pythonic Method Without Duplicating Values — w3tutorials.net
Python’s design (using references for objects) helps here: when you move a value from one key to another, you’re just reassigning the reference, not copying the object itself. The most efficient way to rename a key in-place (modifying the original dictionary) is to use dict.pop().
🌐
Pybites Platform
pybitesplatform.com › bites › rename-keys
Pybites Platform | Master Python Through Hands-On Coding
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 ...