Renaming the keys of a dictionary

29.5k views Asked by At

How to change a key in a Python dictionary?

A routine returns a dictionary. Everything is OK with the dictionary except a couple keys need to be renamed. This code below copies the dictionary entry (key=value) into a new entry with the desired key and then deletes the old entry. Is there a more Pythonic way, perhaps without duplicating the value?

my_dict = some_library.some_method(scan)
my_dict['qVec'] = my_dict['Q']
my_dict['rVec'] = my_dict['R']
del my_dict['Q'], my_dict['R']
return my_dict
1

There are 1 answers

1
Bhargav Rao On BEST ANSWER

dict keys are immutable. That means that they cannot be changed. You can read more from the docs

dictionaries are indexed by keys, which can be any immutable type

Here is a workaround using dict.pop

>>> d = {1:'a',2:'b'}
>>> d[3] = d.pop(1)
>>> d
{2: 'b', 3: 'a'}