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.
Method 2: Rename a Key in a Python Dictionary using Python pop() We use the pop method to change the key value name.
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.
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 .
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.
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With