I don't think you need defaultdict
here at all. Why not just use dict.setdefault
method?
>>> d = {}
>>> d.setdefault('p', C('p')).v
'p'
That will of course would create many instances of C
. In case it's an issue, I think the simpler approach will do:
>>> d = {}
>>> if 'e' not in d: d['e'] = C('e')
It would be quicker than the defaultdict
or any other alternative as far as I can see.
ETA regarding the speed of in
test vs. using try-except clause:
>>> def g():
d = {}
if 'a' in d:
return d['a']
>>> timeit.timeit(g)
0.19638929363557622
>>> def f():
d = {}
try:
return d['a']
except KeyError:
return
>>> timeit.timeit(f)
0.6167065411074759
>>> def k():
d = {'a': 2}
if 'a' in d:
return d['a']
>>> timeit.timeit(k)
0.30074866358404506
>>> def p():
d = {'a': 2}
try:
return d['a']
except KeyError:
return
>>> timeit.timeit(p)
0.28588609450770264