1

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.

2
  • Why didn't numpy.array(vehPositions.values()) work? Are the values in different order or wrong values? Commented Jun 29, 2016 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 Commented Jun 29, 2016 at 13:55

1 Answer 1

7

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]])
Sign up to request clarification or add additional context in comments.

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.