1

I have the following dictionary:

DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", 
"key4": "AAA"}]}

I want to change "records" with for example "XX" so I will have the following:

DATA = {"XX": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": 
"AAA"}]}

How can I do this? Thank you.

Jane
  • 65
  • 7

1 Answers1

1

You can't change a string dictionary key directly in the way you have presented. The reason for this is that the key itself- which again, is a string, or str object- is immutable. This would not necessarily be true for other types of keys, such as for a user-defined object.

Your only option is to add the new key to the existing dictionary, or create a new dictionary with the key you want.

You can assign a new dictionary to the same name, DATA, and add the entry you want to the new dictionary (the old one will eventually be garbage collected):

DATA = {'XX': DATA['records']}

IMPORTANT: Note that any other references to the old DATA dictionary will NOT be updated! For this reason, the new dictionary approach is probably not what you want.

Alternatively, if it is acceptable to keep the records key in your dictionary, you can simply add the XX member to the dictionary and point it to the same value:

DATA['XX'] = DATA['records']

Lastly, if you both want to keep the original dictionary AND remove the records key from it, you will have to do that in two steps:

DATA['XX'] = DATA['records']
del DATA['records']

OR:

DATA['XX'] = DATA.pop('records')

Note that the last suggestion still occurs in two steps even though it is one line of code.

Rick
  • 43,029
  • 15
  • 76
  • 119