Search code examples
pythonpython-3.x

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


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.


Solution

  • This solution modifies the dictionary d in-place. If performance is not a concern, you could do the following:

    d = {"a": 1, "b": 2, "c": 3, "d": 4}
    replacement = {"b": "B"}
    
    for k, v in list(d.items()):
        d[replacement.get(k, k)] = d.pop(k)
    
    print(d)
    

    Output:

    {'a': 1, 'B': 2, 'c': 3, 'd': 4}
    

    Notice that the above solution will work for any numbers of keys to be replaced. Also note that you need to iterate over a copy of d.items() (using list(d.items())), as you shouldn't iterate over a dictionary while modifying its keys.