Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 807
Flimm Avatar asked Dec 05 '19 13:12

Flimm


People also ask

Can you rename a key in dictionary Python?

Method 2: Rename a Key in a Python Dictionary using Python pop() We use the pop method to change the key value name.

How do you change the name of a dictionary key?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

How do I change the order of a dictionary in Python?

So you would have to construct a new OrderedDict by looping over the key:value pairs in the original object. There is no OrderedDict method that will help you. So you could create a tuple to represent the idea order of the keys , and then iterate over that to create a new OrderedDict .

Does dict keys preserve order?

It's a dictionary subclass specially designed to remember the order of items, which is defined by the insertion order of keys. This changed in Python 3.6. The built-in dict class now keeps its items ordered as well.


2 Answers

foo = {'c': 2, 'b': 4, 'J': 7}
foo = {key if key != 'b' else 'B': value for key, value in foo.items()}
foo
Out[7]: {'c': 2, 'B': 4, 'J': 7}
like image 143
Pablo de Luis Avatar answered Sep 20 '22 04:09

Pablo de Luis


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.

like image 41
Dani Mesejo Avatar answered Sep 20 '22 04:09

Dani Mesejo