16

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
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
BarryPye
  • 1,975
  • 2
  • 18
  • 19

1 Answers1

44

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'}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • This will throw an error if the key doesn't exit. Workaround would be d[new_key] = d.pop(old_new, default_value) eg: d[3] = d.pop(0, -1) if 0 is not in d.keys() it will assign -1 instead of throwing an error. – RevolverRakk Jun 07 '22 at 03:08