[Python] How to rename a dictionary key and keep the order in python?

Discussão em 'Python' iniciado por Stack, Setembro 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a json file to store the data for an app. This json file has this dict in it:

    {
    "Survival": {
    "text": "Survival",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\Survival\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    },
    "Creative": {
    "text": "Creative",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\Creative\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    },
    "Redstone": {
    "text": "Redstone",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\Redstone\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    },
    "Create": {
    "text": "Create",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\Create\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    },
    "1.21": {
    "text": "1.21",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\1.21\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    },
    "Ice Boat": {
    "text": "Ice Boat",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\Ice Boat\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    },
    "Mods Lohan": {
    "text": "Mods Lohan",
    "directory": "C:\\Users\\Famille Arcand\\Downloads\\Mods\\Mods Lohan\\",
    "fg_color": "#1e69a4",
    "hover_color": "#144870"
    }
    }


    I am reading from it and assigning it to the var buttons_data. Then i modify the values nested a specified key (for example the value of "text" inside "Survival" will be set to "Survival Mods".) but i also need to change the name of the key (The name needs to be the same as the "text" value) and keep the order.

    I tried this:

    def rename_key(d, old_key, new_key):
    return {new_key if k == old_key else k: v for k, v in d.items()}

    with open(buttons, 'r') as json_file:
    buttons_data = json.load(json_file)

    for button in list(buttons_data.keys()):
    if button == text:
    buttons_data[button]["text"] = new_text
    buttons_data[button]["directory"] = new_directory
    buttons_data[button]["fg_color"] = new_fg_color
    buttons_data[button]["hover_color"] = new_hover_color
    rename_key(buttons_data, text, new_text)
    break


    My issue is that the function rename_key() works when using a dict written in the script (when i define a var manually to be the exact same thing as the json file) but not when i am using a dict in a json file, even when the are the same.

    Continue reading...

Compartilhe esta Página