sorting a dictionary

Alex Martelli aleax at
Fri Feb 21 17:48:25 CET 2003

jcm wrote:

> user at domain.invalid wrote:
>> How about creating a sorted dictionary then? That is, add elements
>> to the dictionary in the order they are supposed to be in.
>> Is that not possible?
> Python dictionaries are unordered.  The best you can probably do is to
> keep a separate list of sorted keys.

As Mr (or Ms) User seems to want to preserve the order in which elements
are added, rather than actually "sorting", he or she might get away with
a simple subclass of dict, such as:

class mydict(dict):

    def __init__(self):  # presumably must start out empty
        self.orderedkeys = []

    def __setitem__(self, key, value):
        if key not in self: self.orderedkeys.append(key)
        dict.__setitem__(self, key, value)

plus, perhaps, other functionality he or she might need (__iter__
if the need is to iterate on the dictionary in the order in which
keys were added to it, __delitem__ if one needs to support key
deletion too -- not too bad anyway, unless one gets into the hairy
details such as, what "order" should be used if one calls update
on such an "order-preserving dictionary"?).



More information about the Python-list mailing list