[clug] Two level python iterator

Francis Markham fmarkham at gmail.com
Wed Dec 8 21:13:08 MST 2010


Depending on your use case, you could avoid having a new class wrapping a
dict of dicts, and instead have a dict of tuples:

# main
 store = {}

# with a bit of hand waving store a bunch of data
 store[i,j] = data

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

On 9 December 2010 15:07, jm <jeffm at ghostgun.com> wrote:

> Thanks. That was it. After posting the original message I keep playing with
> the code, but couldn't work out why I was getting generator type object is
>  the print statement in main's for-loop. It turns out I had almost exactly
> the same code as you do, but I'd put it in the next() method instead of the
> __iter__() method as you do.
>
> Thanks again,
>
> Jeff.
>
>
> On 9/12/10 2:22 PM, Jason wrote:
>
>> 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:
>>
>>
> --
> linux mailing list
> linux at lists.samba.org
> https://lists.samba.org/mailman/listinfo/linux
>


More information about the linux mailing list