I'm trying to understand how multi dimensional dictionary works in Python. Say, I want to create a 3 dimensional dictionary to store average temperature of the month for each year, a data structure like {2001: {'Jan': {Temp: 20}, 'Feb': {Temp: 25}}}
For 2 dimensional, I learned from this post that I can use defaultdict like below
from collections import defaultdict
d = defaultdict(dict)
d[2001]['Jan'] = 20
However, this approach gives KeyError for 3 dimensional dictionary like below:
from collections import defaultdict
d = defaultdict(dict)
d[2001]['Jan']['Temp'] = 20
I also learned the following approach using dict.setdefault method:
d = dict()
d.setdefault(2001, dict()).setdefault('Jan', dict())['Temp'] = 20
This works but is not very easy to use.
I want to know why the defaultdict method works for 2 dimensional but not 3 dimensional dictionary. I tried to create a CustomDict Class like the one below. But it also only works for 2 dimensional dictionar and will give a key error for 3 dimensional.
class mydict(dict):
def __getitem__(self, key):
if key not in self:
self[key] = {}
return super().__getitem__(key)
a = mydict()
a[2001]['Jan'] = 20