Mechanic Mechanic - 1 year ago 583
Python Question

Python Dict to numpy multidimensional array

I have a python dictionary with keys

with each key holding the location co-ordinates in a tuple such as

{0:(x1,y1), 1:(x2,y2), 2:(x3,y3), ....., n-1:(xn,yn)}

I want to create a multidimensional array like

coordinates= np.array([
[x1, y1],
[x2, y2],
[xn, yn]

I have tried using
array = numpy.array(vehPositions.values())
but could not get the expected result.

Answer Source

If you're using python 3.x you should cast explicitly to list as the values() method of dict will return a dict_values object.

You should do:

array = numpy.array(list(vehPositions.values()))

To create your list of lists from the tuple values in your dictionary and build your array, you will not need an explicit cast to list:

array = numpy.array([list(v) for v in vehPositions.values()])

Be careful to not use a generator expression as this will return an array containing a generator object:

>>> numpy.array(list(v) for v in vehPositions.values())
array(<generator object <genexpr> at 0x03B60AA8>, dtype=object)

The trial below demonstrates the procedure:

>>> d = {0: (1,2), 1: (3,4), 2: (5,6)}
>>> numpy.array([list(v) for v in d.values()])
array([[1, 2],
       [3, 4],
       [5, 6]])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download