I am trying to get a dictionary that looks like this:
{1:{2:{3:{4:'foo'}}}}
to look like this:
'foo': [1,2,3,4]
The dictionary is nested to an unknown depth. This is definitely testing my recursion knowledge.
So far I have this. I think this works. However, I am wondering if there is a more pythonic way of doing this:
def denest(nested_dict):
denested_dict = {}
for k, v in nested_dict.items():
if isinstance(v, dict):
sub_dict = denest(v)
for t, s in sub_dict.items():
sub_dict[t] +=[k]
denested_dict.update(sub_dict)
else:
denested_dict[v] = [k]
return denested_dict