I have a dictionary which contains dictionaries, which may in turn contain dictionaries ad infinitum. I want to change every key in all of the dictionaries, with the exception of the keys which map to one of the nested dictionaries. I understand that the keys are immutable, what I want to do something like this:
layer[item + '_addition'] = layer.pop(item)
What I have right now is:
def alterKeys(item, layer=topLevelDict):
if isinstance(item, dict):
for i in item:
alterKeys(item[i], item)
else:
layer[item + '_addition'] = layer.pop(item)
This doesn't work, as it will continually travel recursively down the tree till the last line tries to pop a value from the dict, instead of a key, which raises a KeyError. I know I'm close to a solution, but I've been thinking about this for a few minutes and I can't seem to figure it out.