Why are there no ordered dictionaries?

Bengt Richter bokr at oz.net
Tue Nov 22 18:05:20 EST 2005


On 22 Nov 2005 11:18:19 -0800, "Kay Schluehr" <kay.schluehr at gmx.net> wrote:

>Bengt Richter wrote:
>> On Mon, 21 Nov 2005 01:27:22 +0100, Christoph Zwerschke <cito at online.de> wrote:
>
>> Note that is isn't hard to snap a few pieces together to make an ordered
>> dict to your own specs. But IMO it belongs in pyPI or such, not in the system
>> library. At least until it gets a lot of mileage -- and MMV ;-)
>
>It's also not very hard to write a hex2ascii converter. That's the
>reason why 20 incompatible versions of it ( coded in C ) exists in my
>department ;)
Bicycle shed effect, I guess ;-)

>
>Kay
>
>PS. Here is some attempt of my own to implement an odict, following the
>discussion here.
>The implementation highlights just the model and is incomplete:
>
This is essentially the tack I took in modifying odict.py, except I
added optional caching of sorted items, and other minor differences.

>class odict(dict):
>    def __init__(self, create_order = True):
>        dict.__init__(self)
>        self.create_order = create_order
>        self.__cnt = 0
>
>    def __setitem__(self, key, value):
>        val = dict.get(self,key)
>        if val and self.create_order:
>            dict.__setitem__(self, key, (val[0], value))
>        else:
>            self.__cnt+=1
>            dict.__setitem__(self, key, (self.__cnt, value))
>
>    def __getitem__(self, key):
>        return dict.__getitem__(self, key)[1]
>
>    def values(self):
>        return list(zip(*sorted(dict.values(self)))[1])
maybe more directly
         return [v for i,v in sorted(dict.values(self))]
>
>    def keys(self):
>        ks = [(dict.get(self,k)[0],k) for k in dict.keys(self)]
>        return list(zip(*sorted(ks))[1])
or (untested)
     def keys(self):
         return [k for k,v in sorted(dict.items(self), key=operator.itemgetter(1))]
     def items(self):
         return [(k,v[1]) for k,v in sorted(dict.items(self), key=operator.itemgetter(1))]
>
>>>> od = odict()
>>>> od["a"] = 0
>>>> od["b"] = 8
>>>> od.keys()
>["a", "b"]
>
>>>> od = odict(create_order = False)
>>>> od["a"] = 1
>>>> od["b"] = 2
>>>> od["a"] = 3
>>>> od.keys()
>["b", "a"]
>


Regards,
Bengt Richter



More information about the Python-list mailing list