python – Rename a dictionary key
python – Rename a dictionary key
For a regular dict, you can use:
mydict[k_new] = mydict.pop(k_old)
This will move the item to the end of the dict, unless k_new
was already existing in which case it will overwrite the value in-place.
For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2
to two
:
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {two if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, two: 2, 3: 3}
The same is true for an OrderedDict
, where you cant use dict comprehension syntax, but you can use a generator expression:
OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies theyre immutable and cant be modified.
Using a check for newkey!=oldkey
, this way you can do:
if newkey!=oldkey:
dictionary[newkey] = dictionary[oldkey]
del dictionary[oldkey]
python – Rename a dictionary key
In case of renaming all dictionary keys:
target_dict = {k1:v1, k2:v2, k3:v3}
new_keys = [k4,k5,k6]
for key,n_key in zip(target_dict.keys(), new_keys):
target_dict[n_key] = target_dict.pop(key)