How to Convert python list into nested dictionaries in pythonic way [closed]

You should probably not use this in production, but it was fun…

def make_dict_from_list(li):
    temp = output = {}
    for i, e in enumerate(li, 1):
        if i != len(li):
            temp[e] = {}
            temp = temp[e]
        else:
            temp[e] = []
    return output

print(make_dict_from_list(['a']))
print(make_dict_from_list(['a', 'b', 'c']))

Outputs

{'a': []}
{'a': {'b': {'c': []}}}

Leave a Comment