[Python] How do I rename a key while preserving order in dictionaries (Python 3.7+)?

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dictionary, with this value:

    {"a": 1, "b": 2, "c": 3}


    I would like to rename the key b to B, without it losing its second place. In Python 3.7 and higher, dictionaries preserve insertion order, so the order of the keys can be counted on and might mean something. The end result I'm looking for is:

    {"a": 1, "B": 2, "c": 3}


    The obvious code would be to run:

    >>> dictionary["B"] = dictionary.pop("b")
    {'a': 1, 'c': 3, 'B': 2}


    However, this doesn't preserve the order as desired.

    Continue reading...

Compartilhe esta Página