How to View java Maps as Python Dictionaries

| No Comments

On the jython mailing lists, a note regarding bridging of collections. After the flip, I have posted code regarding bridging of java maps and python dictionaries.


# Gives Java Maps the python Dictionary interface
class MapDict(object):
    def __init__(self):
        from java.util import HashMap
        self.wrapped = HashMap()
        
    def __contains__(self, k):
        return self.wrapped.containsKey(k) or self.wrapped.containsValue(k)

    def __delitem__(self, item):
        self.wrapped.remove(item)

    def __eq__(self, other):
        return self.wrapped.equals(other)

    def __getitem__(self, key):
        return self.wrapped.get(key)

    def __hash__(self):
        return self.wrapped.hashCode()

    def __iter__(self):
        try:
            return self.iterator
        except:
            self.iterator = self.wrapped.iterator()
            return self.iterator

    def __len__(self):
        return self.wrapped.size()

    def __ne__(self, other):
        return not self.__eq__(other)
    
    def __setitem__(self, k, val):
        return self.wrapped.put(k, val)

    def __str__(self):
        return self.wrapped.toString()

Leave a comment

Bookmark and Share

Connect with me


qrcode
Add me on AOL
Hasan Diwan

Follow me on Twitter
Ring me at +1 6502844111
See my photos
How about some analytics?

Twitter

Archives

Creative Commons License
This blog is licensed under a Creative Commons License.