[Tutor] words and lengths

Bob Gailer bgailer at alum.rpi.edu
Thu May 17 02:51:52 CEST 2007

Emad Nawfal wrote:
>> Hi All,
>> I'm beginning to learn Python for linguistic research using the 
>> Natural Language Toolkit. I want to write a small piece of code to 
>> count lengths of words and print them a long with the words. I've 
>> tried this but it does not work. What's wrong with it, and how can I 
>> fix it?
>> phrase2 = ['colorless', 'green', 'ideas', 'sleep', 'furiously']
>> lengths = {}
>> for word in phrase2:
>>     lengths = lengths[word, len(word)]
>> print lengths
Try this:

for word in phrase2:
    lengths[word] = len(word)

What you have now  is an attempt to get a dictionary value using word, 
len(word) as a key and replace the dictionary with that value. Should 
fail with KeyError.

Bob Gailer

More information about the Tutor mailing list