Problem with Lists & Index command
Timothy R Evans
tre17 at cosc.canterbury.ac.nz
Mon Jun 14 18:43:25 EDT 1999
Doug Hellmann <doughellmann at mindspring.com> writes:
>
> wordcounts = {}
> for word in document.words():
> try:
> wordcounts[word] = wordcounts[word] + 1
> except KeyError:
> wordcounts[word] = 1
Alternaively, use the `get' method on the dictionary, which will
return a default value if the key is not found. In this case you want
a default value of 0, so the lines become:
wordcounts = {}
for word in documents.words():
wordcounts[word] = wordcounts.get(word,0) + 1
Its not actually any different, just smaller.
--
Tim Evans
More information about the Python-list
mailing list