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
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
Maybe try this, to see if that’s what you’re looking for?
from collections import defaultdict
ddc = defaultdict(lambda: defaultdict(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
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
Maybe try this, to see if that’s what you’re looking for?
from collections import defaultdict
ddc = defaultdict(lambda: defaultdict(int))