Rtrader
Rtrader

Reputation: 947

Creating dictionary from a numpy array "ValueError: too many values to unpack"

I am trying to create a dictionary from a relatively large numpy array. I tried using the dictionary constructor like so:

elements =dict((k,v) for (a[:,0] , a[:,-1]) in myarray)

I am assuming I am doing this incorrectly since I get the error: "ValueError: too many values to unpack"

The numPy array looks like this:

[  2.01206281e+13  -8.42110000e+04  -8.42110000e+04 ...,   0.00000000e+00
    3.30000000e+02  -3.90343147e-03]

I want the first column 2.01206281e+13 to be the key and the last column -3.90343147e-03 to be the value for each row in the array

Am I on the right track/is there a better way to go about doing this?

Thanks

Edit: let me be more clear I want the first column to be the key and the last column to be the value. I want to do this for every row in the numpy array

Upvotes: 0

Views: 1779

Answers (2)

Bi Rico
Bi Rico

Reputation: 25833

This is kind of a hard question on answer without knowing what exactly myarray is, but this might help you get started.

>>> import numpy as np
>>> a = np.random.randint(0, 10, size=(3, 2))
>>> a
array([[1, 6],
       [9, 3],
       [2, 8]])
>>> dict(a)
{1: 6, 2: 8, 9: 3}

or

>>> a = np.random.randint(0, 10, size=(3, 5))
>>> a
array([[9, 7, 4, 4, 6],
       [8, 9, 1, 6, 5],
       [7, 5, 3, 4, 7]])
>>> dict(a[:, [0, -1]])
{7: 7, 8: 5, 9: 6}

Upvotes: 2

Marco de Wit
Marco de Wit

Reputation: 2804

elements = dict( zip( * [ iter( myarray ) ] * 2 ) )

What we see here is that we create an iterator based on the myarray list. We put it in a list and double it. Now we've got the same iterator bound to the first and second place in a list which we give as arguments to the zip function which creates a list of pairs for the dict creator.

Upvotes: 0

Related Questions