question about subclassing dict

Jason Orendorff jason at jorendorff.com
Sat Feb 2 05:08:23 CET 2002


Russell E. Owen wrote:
> I started by defining __iter__. I was then pleased to find that the 
> methods iterkeys, itervalues and iteritems all worked just fine.

They don't seem to return the objects in the right order (which
I gather is the whole point):

>>> x = OrderedDict.OrderedDict()
>>> x['a'] = 'A'
>>> x['z'] = 'Z'
>>> x[3] = 'three'
>>> x[17.5] = 'seventeen and a half'
>>> x[None] = 'nothing much'
>>> list(iter(x))
['a', 'z', 3, 17.5, None]
>>> list(x.iterkeys())
['a', 3, None, 'z', 17.5]
>>> 

Your test code in OrderedDict.py itself doesn't seem to
test the iterfoo() methods.


> Clearly dict is basing those three iterators on the
> iterator returned by __iter__.

I think it's just using its builtin definition of iterkeys().
Anyway, it's easy enough to define the extra methods:

class OrderedDict(dict):
    ...

    def iterkeys(self):
        return iter(self.__keyList)

    def itervalues(self):
        for k in self.__keyList:
            yield self[k]

    def iteritems(self):
        for k in self.__keyList:
            yield (k, self[k])

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list