user2855135
user2855135

Reputation: 85

Iterating through dictionary and numpy array simultaneously

Is there a slick way of iterating through a dictionary of objects, calling a member function of each object and assigning the value to a numpy array. I have the following member function code:

    # Preallocate for Number of Objects in the dictionary
    newTable = numpy.zeros( self.numObj );

    for item, nt in zip( self.dictTable.values(), newTable ):
        dt = item.CalculateDutyCycle() * 100.0


    return newTable    

This doesn't run because my assignment to the numpy array is not done correctly. I can do it correctly using nditer, but was not sure how to combine that iterator with the dictionary table iteration. I was avoiding the traditional 'counter' increment to access the array is there is a more elegant 'pythonic' solution.

Upvotes: 2

Views: 1244

Answers (2)

hpaulj
hpaulj

Reputation: 231385

I don't seen any advantage to using numpy here, since you are iterating over a regular Python list (values()). I'd just do a list comprehension, and convert it into an array later. Also your array is 1d. numpy shines when working with multidimensional objects (as opposed to simple lists).

list_answer = [item.CalculateDutyCycle() * 100.0 for item in self.dictTable.values()]
newTable = np.array(list_answer)

Upvotes: 1

JoshAdel
JoshAdel

Reputation: 68682

You don't have to explicitly increment a counter if you use enumerate. You could do something like:

newTable = numpy.zeros( self.numObj )
for k, item in enumerate(self.dictTable.values()):
    newTable[k] = item.CalculateDutyCycle() * 100.0

Upvotes: 3

Related Questions