3

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".

3
  • 2
    Are you sure you need a np.array of objects? Why not just work with a list e.g. [12] + list(d.values()) Commented Jul 29, 2018 at 4:18
  • 1
    Yeah, you don't really get much benefit out of an array of objects, especially a small one. You can't vectorize any operations for performance, or even get much convenience benefit out of it. Commented Jul 29, 2018 at 4:20
  • In case anyone was still looking: np.array(list(d.values())).flatten() Commented Sep 4 at 19:31

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

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.