[Tutor] Dictionary questions

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 17 Jan 2002 00:04:05 +0100


On  0, Isaac Hall <hall@phyast.nhn.ou.edu> wrote:

(snip explanation of something I can't quite understand but not relevant to
the question)

> supposing I can determine all of this, is there a way to get the key back out
> of a dictonary simply by asking for the content.

Sort of: take all the keys, and for each key, check if its value is the
value we're looking for. Fast for small dictionaries, slow for huge
dictionaries.

It doesn't "feel" fast (and it's O(len(dict))), but in most cases it should
do fine.

for key in dict.keys():
   if dict[key] == valuewerelookingfor: return key
   
 
> if not:
>     is there a better structure to use which will make correlation between key
>     and content (in this case, there will only be one to one mapping) by which
>     I can get one by knowing the other and vice versa

Easiest would be to simply use two dictionaries: one with key->value pairs
and one with value->key pairs. This is possible only because of the
one-to-one mapping, of course.

You could put the two into a class, so that you never forget to update both,
something like

class DoubleDict:
   def __init__(self):
      self.key_to_val = {}
      self.val_to_key = {}
   def set(self, key, value):
      self.key_to_val[key] = value
      self.val_to_key[value] = key
   def get_value(self, key):
      return self.key_to_val[key]
   def get_key(self, value):
      return self.val_to_key[value]
      
Use with

dict = DoubleDict()

dict.set("Key", "Value")

print dict.get_key("Value")

It's just a quick framework of course, but you get the idea.

-- 
Remco Gerlich