I’ve a dictionary which has tuples for keys which I need to transform to a nested key type.
tuple_dict = {(a, b, c): {"f": 5, "d": 6, "e", 4}}
final_dict = {a: {b: {c: {"f": 5, "d": 6, "e", 4}}}}
I’ve got the following code which works for up to 7 levels of nesting, but I feel like there’s a more elegant solution, maybe using recursion, that would work up to n levels of nesting?
Quick note here, I have another function which is creating an empty “shell” dictionary for this to work, would be nice if I could remove that as well.
for key, value in tuple_dict.items():
if no_of_keys == 1:
final_dict[key[0]] = value
elif no_of_keys == 2:
final_dict[key[0]][key[1]] = value
elif no_of_keys == 3:
final_dict[key[0]][key[1]][key[2]] = value
elif no_of_keys == 4:
final_dict[key[0]][key[1]][key[2]][key[3]] = value
elif no_of_keys == 5:
final_dict[key[0]][key[1]][key[2]][key[3]][key[4]] = value
elif no_of_keys == 6:
final_dict[key[0]][key[1]][key[2]][key[3]][key[4]][key[5]] = value
elif no_of_keys == 7:
final_dict[key[0]][key[1]][key[2]][key[3]][key[4]][key[5]][key[6]] = value
else:
print("Cannot have more than 7 keys")