Problem with Lists & Index command

Doug Hellmann doughellmann at
Mon Jun 14 16:00:59 CEST 1999

Benjamin Schollnick wrote:
> But, the most obvious question, is.....
> Can dictionaries be made & manipulated from
> variables?

Of course!

Think of dictionaries as arrays with indexes that can be values other
than numbers.  Indeed, dictionaries are sometimes called "associative
arrays" because thinking about them this way makes them easier to

So, if you have a variable 'entry' with the value "EFGHI" and you want
to use a dictionary to associate the value of another variable entryval
(which is 1) with that value, you could do something like:

entry = 'EFGHI'
entryval = 1
tcmvalues = {}   # create an empty dictionary (similar to creating an
emtpy list with [])
tcmvalues[ entry ] = entryval

This creates an association between the "value" in entryval with the
"key" in entry.

Now, suppose you are writing a program to count the number of times a
word occurs in a document.  In this case, you would want to increment a
counter stored at the appropriate location.  A first try might look
something like this:

wordcounts = {}
for word in document.words():
  wordcounts[word] = wordcounts[word] + 1

But what happens when you see a word you've never seen before?  On the
right side of the = sign we are retrieving the current value of
wordcounts[word] to add one to it.  But if we've never seen the value of
word before, we'll have a problem.  Some languages solve this by
returning a null value of some type.  Python solves the problem by
raising an exception to let you know you have a situation you need to
deal with.  

> Please keep in mind, that I don't know anything about
> dictionaries... The book I'm using hasn't hit 'em yet....
> (I'm not done reading yet)

If you haven't gotten far enough in the book to find a discussion of
dictionaries, you probably haven't seen anything about exception
handling either.  Throwing and catching exceptions is (usually) a way to
simplify program logic.  It is sort of like saying, "try doing X except
when you encounter a problem.  Handle problem type Y like this, handle
problem type Z like this..."  The standard library functions and built
in types usually raise exceptions to indicate problems or special
cases.  The exception raised by a dictionary when you ask for a value
associated with a key that is not present will be an instance of the
class "KeyError."  

The first occurance of a word is a special case, but is not an error. 
That means we can just handle the exception and keep going through the
list of words.

wordcounts = {}
for word in document.words():
    wordcounts[word] = wordcounts[word] + 1
  except KeyError:
    wordcounts[word] = 1

Good luck,

More information about the Python-list mailing list