0

My dict is a dict of {str: {str: list of str}}
ex:

{'hii':{'bye': [1, 2]}}  

what i want:

{'hi':{'bye': [1, 2]}}  

Is there a way to change the 'hii' to just 'hi'?

what I've tried only edits the values and not the keys.

martineau
  • 112,593
  • 23
  • 157
  • 280
user3050527
  • 741
  • 1
  • 7
  • 15
  • 1
    There's no way to change keys as such. You'll need to add a new key with the same value, then delete the old key. – BrenBarn Nov 30 '13 at 19:34
  • **See also**: http://stackoverflow.com/questions/30720673/renaming-the-keys-of-a-dictionary – dreftymac May 13 '17 at 06:29

3 Answers3

16

You do need to remove and re-add, but you can do it one go with pop:

d['hi'] = d.pop('hii')
Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
2

You need to remove the old key/value pair and insert a new one:

d = {'hii': {'bye': [1, 2]}}
d['hi'] = d['hii']
del d['hii']
Simeon Visser
  • 113,587
  • 18
  • 171
  • 175
2

You cannot change a key in a dictionary, because the key object must be hashable, and therefore immutable. Daniel Roseman's answer looks like the most elegant way of accomplishing your goal.

Chris Drake
  • 343
  • 1
  • 7