pythondictionary

Converting a flat dictionary with tuples as keys to a nested dictionary


I have a dictionary which has tuples for keys which I need to transform to a nested dictionary:

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?

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")

Solution

  • Iterate through the elements of the key tuple, creating the nested dictionaries as needed.

    final_dict = {}
    for key, value in tuple_dict.items():
        temp_dict = final_dict
        for k in key[:-1]:
            if k not in temp_dict:
                temp_dict[k] = {}
            temp_dict = temp_dict[k]
        temp_dict[key[-1]] = value