[Tutor] array and dictionary

Dinesh B Vadhia dineshbvadhia at hotmail.com
Sun Sep 21 20:17:19 CEST 2008


Thanks but I've been a bit daft and described the wrong problem which is easy to solve the long way.  Starting again ...

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)
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:

I want to find a faster/efficient way to do this without using the 2 for loops.  Thanks!

Btw, I posted this on the numpy list too to make sure that there aren't any numpy functions that would help.



Message: 5
Date: Sun, 21 Sep 2008 09:15:00 +0100
From: "Alan Gauld" <alan.gauld at btinternet.com>
Subject: Re: [Tutor] array and dictionary
To: tutor at python.org
Message-ID: <gb4vpv$q6i$1 at ger.gmane.org>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";

"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote

> Hi!  Say, I've got a numpy array/matrix of the form:
> [[1 6 1 2 3]
>  [4 5 4 7 0]...
>  [2 1 0 5 6]]
> I want to create a dictionary of rows (as the keys) mapped 
> to lists of non-zero numbers in that row

Caveat, I dont know about numpy arrays.But assuming they 
act like Python lists

You can get the non zeros with a comprehension

nz = [n for n in row if n != 0]

you can get the row and index using enumerate

for n,r in enumerate(arr):

So to create a dictionary, combine the elements somethng like:

d ={}
for n,r in enumerate(arr):
    d[n] = [v for v in r if v !=0]

I'm sure you could do it all in one line if you really wanted to!
Also the new any() function might be usable too.

All untested....


Alan Gauld
Author of the Learn to Program web site

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080921/4ddd97df/attachment.htm>

More information about the Tutor mailing list