[Tutor] referencing a dictionary

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Mon, 17 Jul 2000 13:25:40 -0700 (PDT)


On Mon, 17 Jul 2000, brian callahan wrote:

>   my idea is to use a raw_input string, to search a dictionary that contains 
> all the characters in the raw_input string with a value, and then i want to 
> sum the values.  my script is used to take a the amino acid sequence of a 
> protein and then give back the molecular weight.  i've been using the 
> 'learning python' book but im getting impatient.

Can you give an example of what sort of input you're going to parse out of
raw_input()?

I'll assume that you're already familiar with dictionaries from another
language.  As a crash course, here are some the basic operations on
dictionaries ("hashtables"):


Creating an empty hashtable:

  myhash = {}


Creating a hashtable with initial entries:

  myhash = {'tryptophan' : 0.3, 'lysine': 0.44, 'methionine': 0.76}


Looking up an entry, given a known key:

  myhash['tryptophan']


Adding a new key/value pair into a dictionary:

  myhash['glutamic acid'] = 0.90


Getting all the keys as a list:

  myhash.keys()


Checking if a key exists in the hash:

  if myhash.has_key('tyrosine'):  ...


With these, you should be able to use dictionaries productively.  If you
have any questions, or would like to see an extended example, just email
tutor@python.org again.  Good luck!