defautovivify(levels=1, final=dict): '''Returns a nested defaultdict with a set number of levels and defined final structure. ''' return (defaultdict(final) if levels < 2else defaultdict(lambda: autovivify(levels - 1, final))) words = autovivify(5, int) words["sam"][2012][5][25]["hello"] += 1 words["sue"][2012][5][24]["today"] += 1 defconvert_nested_dd(dd): '''Converts a nested defaultdict back into a native dictionary. ''' return {k:convert_nested_dd(v) for k,v in dd.items()} if isinstance(dd, defaultdict) else dd