[Tutor] array and dictionary
Kent Johnson
kent37 at tds.net
Sun Sep 21 22:50:36 CEST 2008
On Sun, Sep 21, 2008 at 2:17 PM, Dinesh B Vadhia
<dineshbvadhia at hotmail.com> wrote:
> Given a (numpy) array how do you create a dictionary of lists where the list
> contains the column indexes of non-zero elements and the dictionary key is
> the row index. The easy way is 2 for loops ie.
>
> import numpy
> from collections import defaultdict
> A =
> [[1 6 1 2 3]
> [4 5 4 7 0]
> [2 0 8 0 2]
> [0 0 0 3 7]]
>
> dict = defaultdict(list)
Don't use names of builtins as variable names!
> I = A.shape[0]
> J = A.shape[1]
> for i in xrange(0, I, 1):
> for j in xrange(0, J, 1):
> if a[i,j] > 0:
> dict[i].append(j)
>
> I want to find a faster/efficient way to do this without using the 2 for
> loops. Thanks!
Not sure about faster but this could be done with list/generator comprehensions:
In [37]: A = \
....: [[1, 6, 1, 2, 3],
....: [4, 5, 4, 7, 0],
....: [2, 0, 8, 0, 2],
....: [0, 0, 0, 3, 7]]
In [38]: d = dict( (i, [j for j, val in enumerate(row) if val > 0])
for i, row in enumerate(A))
In [39]: d
Out[39]: {0: [0, 1, 2, 3, 4], 1: [0, 1, 2, 3], 2: [0, 2, 4], 3: [3, 4]}
Kent
More information about the Tutor
mailing list