I am trying to create a python dictionnary that is 4 levels deep, I did it with a couple of conditions but I wondered if anyone knew of a better looking solution (and more efficient also).
A simplified example is the following:
data = {'a': 5}
dict_to_fill = {}
for key_string in key_string_list:
first_key = key_string[0]
second_key = key_string[1]
third_key = key_string[2]
fourth_key = key_string[2]
if not first_key in dict_to_fill:
dict_to_fill[first_key] = {}
if not second_key in dict_to_fill[first_key]:
dict_to_fill[first_key][second_key] = {}
if not third_key in dict_to_fill[first_key][second_key]:
dict_to_fill[first_key][second_key][third_key] = {}
dict_to_fill[first_key][second_key][third_key][fourth_key] = data
What I would ideally like is to simply do this
dict_to_fill[first_key][second_key][third_key][fourth_key] = data
Where all the index errors are replaced by the creation of a dict so that I don't have to through all those conditions.