[Tutor] Keeping Dictonary Entries Ordered

John Fouhy john at fouhy.net
Fri Feb 13 03:41:01 CET 2009


2009/2/13 Eric Dorsey <dorseye at gmail.com>:
> Alan, can you give a short snippet of what that would look like?  I was
> trying to code out some idea of how you'd retain insertion order using
> another dict or a list and didn't get anywhere.

Here's something basic:

class o_dict(dict):
    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)
        self.__keylist = []

    def __setitem__(self, key, val):
        dict.__setitem__(self, key, val)
        if key not in self.__keylist:
            self.__keylist.append(key)

    def __iter__(self):
        return iter(self.__keylist)

It will do the right thing if you do 'for key in odict:', but not for
things like iteritems().  It will break if you delete keys from the
dictionary, and the 'key not in self.__keylist' test will get slow if
you have lots and lots of keys.  It will also not do what you want if
you initialise it as something like: o_dict(foo=1, bar=2)

All of which goes to show that you're probably better off looking for
an implementation online, since someone else is bound to have tied off
all the issues :-)

-- 
John.


More information about the Tutor mailing list