Skip to content

Instantly share code, notes, and snippets.

@alcides
Created May 30, 2009 22:18
Show Gist options
  • Save alcides/120664 to your computer and use it in GitHub Desktop.
Save alcides/120664 to your computer and use it in GitHub Desktop.
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