So I wrote this code to dynamically create dictionary entries from variables if the keys provided in those variables do not exist in the dictionary:
example_dict = {'jack' : {'long' : {'color' : 'red'}}}
name = 'jane'
hair = 'short'
color = 'color'
shade = 'blue'
if name not in example_dict:
example_dict[name] = {hair : {color : shade}}
else:
if hair not in example_dict[name]:
example_dict[name][hair] = {color : shade}
else:
if color not in example_dict[name][hair]:
example_dict[name][hair][color] = shade
else:
example_dict[name][hair][color] = shade
print(example_dict)
This is working, but I feel it is clumsy and can be done in a more simple fashion, perhaps even as a one-liner. Would you be able to suggest a better perhaps faster alternative, please?