Created
October 11, 2011 16:14
-
-
Save siwells/1278546 to your computer and use it in GitHub Desktop.
Playing with bimapped dictionaries in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Bimap(dict): | |
| # def alias(self,obj): | |
| def lkey(self, obj): | |
| return self[obj] | |
| def rkey(self, obj): | |
| for key,val in self.iteritems(): | |
| if val is obj: | |
| return key | |
| raise ValueError("object not in dictionary %s" % obj) | |
| if __name__ == '__main__': | |
| dic1 = {'ach01':'pc01', 'ach02':'pc02'} | |
| bm = Bimap(dic1) | |
| print bm.rkey('pc01') | |
| print bm.lkey('ach01') | |
| try: | |
| print bm.rkey('hello') | |
| except ValueError as inst: | |
| print "KEY ERROR: %s" % inst | |
| try: | |
| print bm.lkey('world') | |
| except KeyError as inst: | |
| print "KEY ERROR: %s" % inst |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment