python – Change the name of a key in dictionary

python – Change the name of a key in dictionary

Easily done in 2 steps:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

Or in 1 step:

dictionary[new_key] = dictionary.pop(old_key)

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

>>> dictionary = { 1: one, 2:two, 3:three }
>>> dictionary[ONE] = dictionary.pop(1)
>>> dictionary
{2: two, 3: three, ONE: one}
>>> dictionary[ONE] = dictionary.pop(1)
Traceback (most recent call last):
  File <input>, line 1, in <module>
KeyError: 1

if you want to change all the keys:

d = {x:1, y:2, z:3}
d1 = {x:a, y:b, z:c}

In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {a: 1, b: 2, c: 3}

if you want to change single key:
You can go with any of the above suggestion.

python – Change the name of a key in dictionary

popnfresh

>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>> 

Leave a Reply

Your email address will not be published. Required fields are marked *