2

I would like to concatenate all numpy arrays (all same size) in a python dict to a new array.

dict = {'some_key_1':np.array([1,2,3,4]), 'some_key_2':np.array([2,3,4,5]), ...}

the result that I would like to see is:

result = np.array([[1,2,3,4],[2,3,4,5]])

whats the best way to do that?

Edit: Solution seems to be slightly different for python 2 and 3. The accepted answer solves it for python 3.

3
  • How about np.array(dict.values())? If you have a ragged number of elems that could be an issue. Commented May 5, 2017 at 13:29
  • result is an object that I can't work with, not an array unortunately: array(dict_values([[1,2,3,4],[2,3,4,5]])) Commented May 5, 2017 at 13:30
  • I have posted a python-version independent solution utilizing vstack, have a look :) Commented May 5, 2017 at 13:56

3 Answers 3

1

In Python 3, you'd need to convert the dict.values() to a list first.

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. (https://docs.python.org/3/library/stdtypes.html#typesmapping)

import numpy as np
data = {'some_key_1':np.array([1,2,3,4]), 'some_key_2':np.array([2,3,4,5])}
print(np.array(list(data.values())))
# [[1 2 3 4]
# [2 3 4 5]]

You get a 2-D array, with rows in a random order (Python dicts are unordered).

To get a 1-D array, you can use np.concatenate:

print(np.concatenate(list(data.values())))
# [1 2 3 4 2 3 4 5]

If the order is important, you could use a list of tuple or an OrderedDict instead of a dict.

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

1 Comment

Thank's thats it! I use python 3.5
1

Probably the easiest way:

result = np.array(list(dict.values()))

With list, the dictionary's values will be stored in a list (i.e. one obtains a list where each item is a numpy array). This list of numpy arrays can then itself be converted to a numpy array by applying np.array().

You should not use dict as a name for your dictionary, though, as this shadows the built-in name dict. Instead, use e.g.:

result = np.array(list(dct.values()))

And make sure to rename your dictionary to dct.

Comments

0

You can get all values of a dictionary by using dictionary.values() and pass it to numpy.array

import numpy as np
np.array(list(dict.values()))

Please do not use dict as name it is a reserved keyword in python

Example

import numpy as np
data = {'some_key_1':np.array([1,2,3,4]), 'some_key_2':np.array([2,3,4,5])}
np.array(list(data.values()))

Output

array([[2, 3, 4, 5],
       [1, 2, 3, 4]])

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.