faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 12 people (75%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Bi-directional dictionary

Jul 5th, 2000 10:01
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 186, Stephan Houben


"""
Packages: basic_datatypes.dictionaries
"""
# bidict.py
""" A bidirectional dictionary, based on code posted to the Python ML, by
Stephan Houben."""
from UserDict import UserDict
class BiDict(UserDict):
    def __getitem__(self, item):
        return self.data[item]
    def __setitem__(self, item, value):
        self.__erase(item)
        self.__erase(value)
        self.data[item] = value
        self.data[value] = item
    def __delitem__(self, item):
        del self.data[self.data[item]]
        #the second item is already be erased iff item == self.data[item]
        try:
            del self.data[item]
        except KeyError:
            pass	
    #try to delete an item	
    def __erase(self, item):	
        try:
            del self.data[self.data[item]]
        except KeyError:
            pass	    
    def __repr__(self):
        return repr(self.data)		
if __name__ == '__main__':
    test = BiDict()
    test['a'] = 'b'
    test['c'] = 'd'  
    print 'test =', test
    test['b'] = 'c'    
    print 'test =', test
    test['c'] = 'c'
    print 'test =', test
    del test['c']
    print 'test =', test