Search code examples
python-3.xdefaultdict

How to Convert python list into nested dictionaries in pythonic way


I am new to python and trying to convert my input list which is ["a", "b", "c"] into nested dictionaries like {"a":{"b":{"c":{}}}}


Solution

  • 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': []}}}