Issue
The dictionary in question is a embedding and I would like to write a function that automatically initializes a numpy array to the correct dimensions. To do that I would like to write something like
np.zeros(embedding.first().shape)
which obviously doesn't work.
Obviously I can write
np.zeros(embedding[list(embedding)[0]].shape)
however that feels quite unpythonic (and slow), so I wonder if there is a better way.
Solution
As far as I could understand your goal is initialization of NumPy array with the same dimensions as your first element is?
If so, embedding[list(embedding)[0]].shape
is a bit unwieldy as you said yourself, more efficient way would be using next
and iter
functions - which does allow you to skip conversion (the part where you need to convert entire keys view into list).
You'd do it as:
import numpy as np
# Assuming 'embedding' is your dictionary
first_key = next(iter(embedding))
array_shape = embedding[first_key].shape
zero_array = np.zeros(array_shape)
The next(iter(embedding))
line of code fetches first key from the dictionary iterator.
Answered By - str1ng
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.