[Tutor] iteritems() vs items()
Kent Johnson
kent37 at tds.net
Sun Nov 13 06:24:15 CET 2005
Tim Johnson wrote:
> I need to get up to speed on iterators. I learned python 1.5~ via
> Alan G's book ...
> For an example, I've written a subclass of dict where keys are kept in
> a ordered fashion is a list called __keys:
>
> #Here is my items function:
> def items(self):
> """ Return all pairs in order of addition"""
> return [(key,self.__dict[key]) for key in self.__keys]
>
> #And here is my iteritems function (currently does exactly the same thing)
> def iteritems(self):
> """ At this implementation, does exactly the same thing as
> method items()"""
> for key in self.__keys:
> yield (key,self.__dict[key])
I think you have it right. Your two methods don't do the same thing - items() returns a list of key, value pairs; iteritems() returns a generator which yields key, value pairs. This is the correct behaviour.
Kent
--
http://www.kentsjohnson.com
More information about the Tutor
mailing list