Reputation: 2385
I'm wondering if there's a more clever way to create a default dict from collections. The dict should have an empty numpy ndarray as default value.
My best result is so far:
import collections
d = collections.defaultdict(lambda: numpy.ndarray(0))
However, i'm wondering if there's a possibility to skip the lambda term and create the dict in a more direct way. Like:
d = collections.defaultdict(numpy.ndarray(0)) # <- Nice and short - but not callable
Upvotes: 14
Views: 15729
Reputation: 4191
Another way is the following if you know the array size beforehand:
new_dict = defaultdict(lambda: numpy.zeros(array_size))
Upvotes: 4
Reputation: 1123250
You can use functools.partial()
instead of a lambda:
from collections import defaultdict
from functools import partial
defaultdict(partial(numpy.ndarray, 0))
You always need a callable for defaultdict()
, and numpy.ndarray()
always needs at least one argument, so you cannot just pass in numpy.ndarray
here.
Upvotes: 24