[clug] Two level python iterator

Jason j.lee.nielsen at gmail.com
Wed Dec 8 20:22:40 MST 2010


I dont use these features much myself but I think this will do what you want

 from collections import defaultdict

class TwoLevel(object):

     def __init__(self):
         self.data = defaultdict(dict)

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

     def __iter__(self):
         for firstLevel in self.data.values():
	    for secondLevel in firstLevel.values():
                 yield secondLevel
         raise StopIteration()

if __name__ == "__main__":
     store = TwoLevel()
     # with a bit of hand waving store a bunch of data
     for i in range(0, 10):
         for j in range(20,30):
           store.add_data(i,j, "%s: %s"%(i,j))
     # do something with entries
     for entry in store:
         print entry

Jason


On Thu, 09 Dec 2010 13:56:15 +1100, jm <jeffm at ghostgun.com> wrote:

> 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