14

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
3
  • 4
    Why do you want to use ndarray with defaultdict? You'll have to create a new array each time to insert an item to an existing key, better use list which supports append operation. Commented Jul 29, 2014 at 11:38
  • np.concat() can be used to accumulate arrays. If the arrays are large and few, this may be more efficient. So, I like the proposed solution above. Commented Jun 6, 2018 at 5:39
  • Accumulation: base = defaultdict(lambda : np.ndarray(0)); base = np.concatenate((base, new_array) Commented Jun 6, 2018 at 6:03

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm new to Numpy. Is Ashwini correct when he says 'You'll have to create a new array each time to insert an item to an existing key. Better use list which supports append operation'?
@Phillip yes, they are correct. Numpy arrays have a fixed size; see How to extend an array in-place in Numpy?.
4

Another way is the following if you know the array size beforehand:

new_dict = defaultdict(lambda: numpy.zeros(array_size))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.