1

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
  • 119,623
  • 25
  • 170
  • 301
user3050527
  • 881
  • 1
  • 8
  • 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

17

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

d['hi'] = d.pop('hii')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
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
  • 118,920
  • 18
  • 185
  • 180
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
  • 353
  • 1
  • 7