Search code examples
pythondefaultdict

defaultdict of defaultdict of int


How do I do defaultdict(defaultdict(int))?

I tried the nested defaultdict method:

def ddict():
    return defaultdict(ddict)

I am looking to do the following:

m['a']['b'] += 1


Solution

  • Try this:

    from collections import defaultdict
    
    m = defaultdict(lambda: defaultdict(int))
    m['a']['b'] += 1
    

    Note if you want more depth, you can still use a recursive approach:

    def ddict(some_type, depth=0):
        if depth == 0:
            return defaultdict(some_type)
        else:
            return defaultdict(lambda: ddict(some_type, depth-1))
    
    m = ddict(int, depth=2)
    m['a']['b']['c'] += 1