A sorted map type.

Ype Kingma ykingma at accessforall.nl
Fri Apr 13 05:36:50 EDT 2001


Antoon, Rikard,

Rikard Bosnjakovic wrote:
> 
> apardon at trout.vub.ac.be wrote:
> 
> > What I need is a map type that allow you to visit
> > all members in key order. Also the possibility
> > to look for the next in line after a search
> > would be nice. Is there a module that already
> > implements such a maptype or do I have to do
> > it myself?
> 
> We had this discussion 2-3 weeks ago. Check some digests.

I missed this discussion. But as a jython user I tried
to subclass java.lang.TreeMap, which is a sorted map.
In Jython this worked like a charm: (of the top of my head,
the real version is a reboot away)


import java

class pythonComparator(java.util.Comparator):
    def compare(self, k1, k2): return cmp(k1, k2)
    def equals(self, comp): return self is comp

class TreeMap(java.util.TreeMap):
    def __init__(self): java.util.TreeMap.__init__(pythonComparator)
    # replace java object ordering by jython cmp().

    def __getitem__(self, k): return self.get(k)
    def __setitem__(self, k, v): self.put(k, v)
    def __delitem__(self, k): self.remove(k)

    def keys(self): return self.keySet()
    # no need to override values()


tm = TreeMap()
tm[4] = 'four'
tm[1] = 'one'
tm[3] = 'three'
tm[2] = 'two'
print tm.values()

Output is:

['one', 'two', 'three', 'four']


I wish I knew why the java Set returned by tm.values() behaves like a python list,
but that doesn't really matter: it works.
(I would be faster to implement the pythonComparator directly in java.)

Adding a print statement to the compare() method easily verifies the tree like
behaviour at insertions and deletions.

So, you can have a sorted map in Jython, provided that your Java has Collections
(java 1.2 and later iirc.)
For CPython this means that you might implement a C treemap as a native module,
I don't know whether this has been done.

Kind regards,
Ype Kingma

(cross posted to comp.lang.python and jython-users at lists.sourceforge.net)

-- 
email at xs4all.nl



More information about the Python-list mailing list