[clug] Two level python iterator

jm jeffm at ghostgun.com
Wed Dec 8 19:56:15 MST 2010


One for the python developers out there.

I have a class which stores data in a hash of a hash and I which I wish 
to iterate over all the entries. Something like that shown below. What 
do I write for the __iter__ and next methods so that I can loop over the 
data with one for loop? Been thinking in languages other than python 
lately and just can't see the answer at the moment.

class TwoLevel:
....
    def add_data(self, idx1, idx2, value):
      self.data[idx1][idx2] = value

   def __iter__(self):
      # what goes here

   def next(self):
      # and here


# main
   store = TwoLevel()

# with a bit of hand waving store a bunch of data
   store.add_data(i,j, data)

# do something with entries
for entry in store:
     print entry


Jeff.


More information about the linux mailing list