Created
May 30, 2009 22:18
-
-
Save alcides/120664 to your computer and use it in GitHub Desktop.
This file contains 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 ReverseDict(object): | |
""" Creates a reverse dictionary, and keeps the connection. Only key access works. """ | |
def __init__(self,dic): | |
self.dic = dic | |
def __getitem__(self,p): | |
for k in self.dic: | |
if self.dic[k] == p: | |
return k | |
# here we have a simple dictionary | |
d = { | |
1: "apple", | |
2: "pear" | |
} | |
# printing the values | |
print d[1] | |
print d[2] | |
# create a reverse dictionary | |
r = ReverseDict(d) | |
# we can fetch keys from values | |
print r["apple"] | |
print r["pear"] | |
# and if we update the dictionary, it still works | |
d.update({4:"banana"}) | |
print r["banana"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment