Now that we understand nested dictionaries and defaultdicts
, we can get into nested defaultdicts
.
This is concept is extremely powerful as it allows you to build complex dictionaries with a simple initialization. The only caveat is that you need to know the depth of your data structure in advance. Also, you need to know the default type of the terminal values.
If you're wondering how this concept will be useful, think about a situation where you'd want to use a defaultdict
but you actually want the default
type to be defaultdict
.
The first thing we have to do is define our dictionary:
from collections import defaultdict
my_dict = defaultdict(lambda: defaultdict(dict))
Notice that we have to use a lambda
function as the argument to the first defaultdict
. This is because defaultdict
expects a callable (or None
).
If necessary, we could take this concept as far as we need:
my_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
Now, using our original example, we can easily populate our data structure without having to initialize each value.
my_dict['dogs']['rover']['bathed'] = True
my_dict['dogs']['rover']['fed'] = False
my_dict['cats']['sam']['fed'] = True