[Tutor] Dictionaries [Was: Re: string object into reference]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 18 01:03:16 CET 2006


> > My problem is I want to make a string object into a reference to
> > another object.  To be more specific, I'm reading through a text file
> > of amino acids.  The first item on each line is the amino acid name,
> > and a later item is its exposed surface area.

Hi Victor,

It sounds like we'd like to maintain a mapping between amino acids and
their exposed surface areas.  This is traditionally known as a "key-value"
pairing, and there are a few things in Python that we can use to represent
this.  The most direct way of doing this is with a dictionary:

   http://www.python.org/doc/tut/node7.html#SECTION007500000000000000000


Let's show what dictionaries look like:

######
>>> alphas = {'a': "Alpha", 'b' : 'Beta' }
>>> alphas['a']
'Alpha'
>>> alphas['g'] = 'gama'
>>>
>>>
>>> alphas
{'a': 'Alpha', 'b': 'Beta', 'g': 'gama'}
>>> alphas['g'] = 'gamma'
######

In this way, we can collect a bunch of key-value pairs by setting elements
in a dictionary.


This is often prefered to having a variable for each key-value pair.  A
dictionary allows to ask things like this:

######
>>> alphas.keys()          ## What keys have we defined?
['a', 'b', 'g']

>>> alphas.values()        ## What values do we have?
['Alpha', 'Beta', 'gamma']
######

These kind of "bulk" questions are fairly easy to answer if we collect all
the key-value pairs in a single dictionary container, because we're just
asking that one container.

But it's much harder to answer this if we use individual variables for
each key-value pair, since we don't tell the system that those variables
are somehow related as a group --- as far as Python knows, they're just
disconnected variables.


The terminology that the original poster uses ("references to another
object") sounds a lot like the original usage of symbolic "soft"
references in Perl.
(http://www.perl.com/doc/manual/html/pod/perlref.html)

Perl programmers, for the most part, avoid them now because they're so
error prone. So if the original poster is thinking about symbolic
references, then we should encourage the poster to look into dictionaries,
since dictionaries are a fairly direct replacement for that usage.


Best of wishes!






More information about the Tutor mailing list