I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
I give the structure I want them to be like:
['weather', 'season', 'lateness']
and finally get the data in this format:
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
This is the manual way that I thought for achieving this:
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
Can you think of a way to be able to just change the structure I wrote and having the desired result? Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.