defaultdict of defaultdict of int

Question:

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

Asked By: user3222184

||

Answers:

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
Answered By: Julien

Maybe try this, to see if that’s what you’re looking for?

from collections import defaultdict

ddc = defaultdict(lambda: defaultdict(int))
Answered By: Daniel Hao
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.