Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary.values() to numpy array

Tags:

python

numpy

Say I have a dict using python 3:

d = {'w1': np.array([12,11,23]), 'w2':np.array([1,2,3])}

and some variable with an integer say

a=12

How do I turn the dict values and integer into one numpy array so that it looks like this?

array([12, array([12, 11, 23]), array([1, 2, 3])])

I've tried:

np.array([a,(list(d.values()))],dtype=object)

and I get:

array([12, list([array([12, 11, 23]), array([1, 2, 3])])], dtype=object)

but I don't want the list in the second index, I want it to be "unpacked".

like image 416
jakko Avatar asked Jul 21 '26 19:07

jakko


1 Answers

If you don't want to put the arrays in an inner list, just don't put them in a list:

>>> np.array([a, *d.values()], dtype=object)
array([12, array([12, 11, 23]), array([1, 2, 3])], dtype=object)

Or, if you're on an older Python and can't unpack into a list display, create the list, but add it to another one to get the same flat list:

>>> np.array([a] + list(d.values()), dtype=object)
array([12, array([12, 11, 23]), array([1, 2, 3])], dtype=object)
like image 149
abarnert Avatar answered Jul 24 '26 07:07

abarnert