0

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

user3222184
  • 1,071
  • 2
  • 11
  • 28
  • Welcome back to Stack Overflow - it's been a while. As a refresher, please read [ask]. "I tried the nested defaultdict method:" **How** did you try it? **What happened** when you tried that, and **how is that different** from what you want? – Karl Knechtel Jul 27 '22 at 01:54

1 Answers1

1

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
Julien
  • 13,986
  • 5
  • 29
  • 53