Convert dict to array in NumPy

I would like to take a dictionary dictionary containing floats indexed by int and convert it to numpy.array for use with the numpy library. I am currently manually converting values ​​to two arrays, one for the original indexes and the other for the values. Although I was looking at numpy.asarray, my conclusion was that I should do something wrong with him. Can someone show an example of how to properly transform such a creature? No need to use numpy.asarray, everything will be done.

from collections import defaultdict
foo = defaultdict( lambda: defaultdict(float) )
#Then "foo" is populated by several
#routines reading results from a DB
#
#As an example
foo[ 7104 ][ 3 ] = 4.5
foo[ 203 ][ 1 ] = 3.2
foo[ 2 ][ 1 ] = 2.7

I would like to have only a multidimensional float array, not a dicts array.

Edit:

Sorry for delay. Here is the code I used to create the first array object containing only the values:

storedArray = numpy.asarray( reduce( lambda x,y: x + y, (item.values() for item in storedMapping.values() ) ) )

, - , dict dict .

+5
2

N M,

N=max(foo)+1
M=max(max(x) for x in foo.values())+1
fooarray = numpy.zeros((N, M))
for key1, row in foo.iteritems():
   for key2, value in row.iteritems():
       fooarray[key1, key2] = value 

. ,

import scipy.sparse
foosparse = scipy.sparse.lil_matrix((N, M))
for key1, row in foo.iteritems():
   for key2, value in row.iteritems():
       foosparse[(key1, key2)] = value 
+4

, NxM, :

myarray = numpy.zeros((N, M))
for key1, row in mydict.iteritems():
   for key2, value in row.iteritems():
       myarray[key1, key2] = value 
+1

All Articles