Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have a python dictionary with keys (0,1,2....n) 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.

share|improve this question
    
Why didn't numpy.array(vehPositions.values()) work? Are the values in different order or wrong values? – Divakar Jun 29 at 13:43
    
I only get a array of type (object) like array(dict_values([(x1,y1),(x2,y2),...])). If i use array(x), it returns me 'numpy.ndarray' object is not callable. If I do array[x], it gives me too many indices for array – Mechanic Jun 29 at 13:55
up vote 3 down vote accepted

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]])
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.