Exploring Bioinformatics with Python

Dictionaries in Python

A common task in many algorithms is to convert one string to another. We often call this the dictionary problem, since it is akin to looking up a name in a phone book. We call the string used to find the entry the key and the string retrieved the value

In early programming languages, programmers had to implement dictionaries themselves. In many modern programming languages, including Python, dictionaries are included as a built-in type. (In some languages, such as Perl, dictionaries are called hashes because of the underlying implementation as a hash table.)

To create a dictionary variable in Python, you assign the empty dictionary, {} to the variable.

>>> aa_name_dict = {}
>>> codons = {}

To add a key/value pair to the dictionary, you index the dictionary with the key and assign the value.

>>> aa_name_dict['A'] = 'Alanine'
>>> aa_name_dict['R'] = 'Arginine'
>>> aa_name_dict['N'] = 'Asparagine'
...
>>> codons['GCA'] = 'A'
>>> codons['GCC'] = 'C'

To look up a value in a dictionary, you index the dictionary with the key.

>>> aa_name_dict['A']
'Alanine'
>>> aa_name_dict['V']
'Valine'
>>> aa_name_dict['Q']
'Glutamine'
>>> codons['AGC']
'S'
>>> codons['GCA']
'A'
>>> codons['AUG']
'M'
>>> aa_name_dict[codons['GUC']]
'Valine'

What happens if the key is not in the dictionary? You get an exception, most precisely, a KeyError.

>>> aa_name_dict['Z']
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
      aa_name_dict['Z']
      KeyError: 'Z'

In some cases, we don't want to raise an error if the key is not in the dictionary. Rather, we want to return a special value (e.g., a '*'). Hence, we must catch the exception. In many cases, you will find it useful to wrap the dictionary lookup in a procedure with a try/except clause.

def codon_to_aa(codon):
    """Convert a codon to the one-letter representation of the corresponding 
       amino acid.  If the codon is invalid, returns the special character
       '*'."""
    try:
        return codons[codon]
    except KeyError:
        return '*'

This page was generated by Siteweaver on Thu Sep 10 13:00:37 2009.
The source to the page was last modified on Thu Sep 10 13:00:36 2009.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/ExBioPy/dictionaries.html.

You may wish to validate this page's HTML

Samuel A. Rebelsky
rebelsky@grinnell.edu