Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn dictionary of lists into a 1D numpy array

I have a Python 3 dictionary holding very long lists (30 million integers each). I would like to stitch all these lists into a single numpy array. How can I do this efficiently?

The following

np.array(my_dict.values())

doesn't seem to work (I get array(dict_values([[...], [....])) as opposed to a flat 1D numpy array).

like image 440
Amelio Vazquez-Reina Avatar asked Dec 02 '22 18:12

Amelio Vazquez-Reina


1 Answers

If you're looking for a flat 1d array, you could just use np.concatenate:

>>> d = {'a': [1, 2, 3, 4, 5], 'b': [1, 2, 3, 4, 5], 'c': [1, 2, 3, 4, 5]}
>>> np.concatenate(list(d.values()))
array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5])
like image 113
Alex Riley Avatar answered Jan 08 '23 16:01

Alex Riley