import collections


def vivify(levels=1, atom=dict):
    """
    Builds a nested {defaultdict} with a fixed depth and a specified type at the deepest level.

    Adopted from (http://en.wikipedia.org/wiki/Autovivification)
    """
    # the embryonic case is a {defaultdict} of type {atom}
    if levels < 2: return collections.defaultdict(atom)
    # otherwise, build a {defaultdict} that is shallower by one level
    return collections.defaultdict(lambda: vivify(levels=levels-1, atom=atom))