An alternative option - depending on your uses, is to use tuples as keys instead of nested dictionaries:
mydict = {}
mydict['foo', 'bar', 'foobar'] = 25
This will work perfectly well unless you want to get a branch of the tree at any point (you can't get mydict['foo'] in this case).
If you knew how many layers of nesting you want, you could also use functools.partial
instead of lambda.
from functools import partial
from collections import defaultdict
tripledict = partial(defaultdict, partial(defaultdict, dict))
mydict = tripledict()
mydict['foo']['bar']['foobar'] = 25
Which some people find more readable, and is faster to create instances of than the equivalent lambda-based solution:
python -m timeit -s "from functools import partial" -s "from collections import defaultdict" -s "tripledefaultdict = partial(defaultdict, partial(defaultdict, dict))" "tripledefaultdict()"
1000000 loops, best of 3: 0.281 usec per loop
python -m timeit -s "from collections import defaultdict" -s "recursivedict = lambda: defaultdict(recursivedict)" "recursivedict()"
1000000 loops, best of 3: 0.446 usec per loop
Although, as always, there is no point optimising until you know there is a bottleneck, so pick what is most useful and readable before what is fastest.