How to use a specific data structure as the default_factory for a defaultdict?

I am currently using a defaultdict of Counter to uniquely count several unpredictable values for unpredictable keys:

from collections import defaultdict, Counter

d = defaultdict(Counter)
d['x']['b'] += 1
d['x']['c'] += 1
print(d)

This gives me the expected result:

defaultdict(<class 'collections.Counter'>, {'x': Counter({'c': 1, 'b': 1})})

I now need to expand the structure of the values in the defaultdict and make it a dict with two keys: the previous Counter and an str:

mystruct = {
    'counter': collections.Counter(),
    'name': ''
}

Is it possible to use a specific data structure (like the above) as the default_factory in defaultdict? The expected result would be that for each nonexistent key in the defaultdict, a new key and value initialized with the structure above would be created.

Best answer

You just need to define your default_factory as a function that returns the dictionary you want to default to:

from collections import defaultdict, Counter
d = defaultdict(lambda: {'counter': Counter(), 'name': ''})
d['x']['counter']['b'] += 1
d['x']['counter']['c'] += 1
print(d)

If you are not familiar with lambdas, this is the same thing as:

def my_factory():
    aDict = {'counter': Counter(), 'name':''}
    return aDict
d = defaultdict(my_factory)