I would like to create a dictionary where I can assign a value several layers deep inside the nested dictionary without explicitly creating the outer layers first. Here's what I'd like to be able to do:
d = {} # or whatever Python object works
d['a']['b']['c'] = 3
Here's what I've tried so far:
If I have a normal dictionary, I can assign a key like so:
d = {}
d['a'] = 1
but not like so:
d['a']['b'] = 2
However, I can use a defaultdict
to do that like so:
from collections import defaultdict
dd = defaultdict(dict)
dd['a']['b'] = 2
However, I still can't do a deeply nested dictionary
from collections import defaultdict
dd = defaultdict(dict)
dd['a']['b']['c'] = 3
I know I could do this with a recursive function but I was hoping there would be a simple way to do this. Is there?
EDIT:
I also tried this but it didn't work:
from collections import defaultdict
dd = defaultdict(defaultdict)
dd['a']['b']['c'] = 3