-6

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

Malik Faiq
  • 433
  • 6
  • 18
M Usman Wahab
  • 53
  • 1
  • 10

1 Answers1

0

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': []}}}
DeepSpace
  • 78,697
  • 11
  • 109
  • 154