Ordered dictionary?

Mel Wilson mwilson at the-wire.com
Tue Jan 27 11:56:14 EST 2004


In article <99dce321.0401231546.5f73d721 at posting.google.com>,
dw-google.com at botanicus.net (David M. Wilson) wrote:
>"Paul McGuire" <ptmcg at users.sourceforge.net> wrote...
>
>> If you really need to access the dictionary in sorted key order, is this so
>> difficult?
>
>That was not the original poster's question. Order is semantic
>information which a dictionary does not record or represent in any
>way.

Wants order of insertion.  Best I can think of is



class OrderedDict (dict):
    "Retains order-of-insertion in the dictionary"
    def __setitem__ (self, key, value):
        dict.__setitem__ (self, key, (len (self), value,) )

    def __getitem__ (self, key):
        return dict.__getitem__ (self, key)[1]

    def ordered_items (self):
        i = [(v, k) for (k, v) in self.items()]
        i.sort()
        return [(k, v[1]) for (v, k) in i]

# end class OrderedDict

if __name__ == '__main__':
    D = OrderedDict()
    D['oranges'] = 41
    D['lemons'] = 22
    D['limes'] = 63

    print D
    print D.ordered_items()



   Possibly other refinenemts:  __init__ that inserts from a
sequence of 2-tuples, keeping a sequence number as a class
attribute instead of using len, etc.

        Regards.        Mel.



More information about the Python-list mailing list