Keeping track of things with dictionaries

Frank Millman frank at chagford.com
Tue Apr 8 05:28:19 EDT 2014


"Chris Angelico" <rosuav at gmail.com> wrote in message 
news:CAPTjJmoRxEhX02ZviHiLO+qi+dD+81smbGGYcPECpHb5E=p4=A at mail.gmail.com...
> On Tue, Apr 8, 2014 at 6:26 PM, Frank Millman <frank at chagford.com> wrote:
>>> words_by_length = {}
>>> for word in open("/usr/share/dict/words"):
>>>    words_by_length.setdefault(len(word), []).append(word)
>>>
>>> This will, very conveniently, give you a list of all words of a
>>> particular length. (It's actually a little buggy but you get the
>>> idea.)
>>>
>>
>> Thanks, that is neat.
>>
>> I haven't spotted the bug yet! Can you give me a hint?
>
> Run those lines in interactive Python (and change the file name if
> you're not on Unix or if you don't have a dictionary at that path),
> and then look at what's in words_by_length[23] - in the dictionary I
> have here (Debian Wheezy, using an American English dictionary - it's
> a symlink to (ultimately) /usr/share/dict/american-english), there are
> five entries in that list. Count how many letters there are in them.
>

I don't have a large dictionary to test with, and a small list of words (ls 
/etc > dict) did not throw up any problems.

Are you saying that

    all([len(word) == 23 for word in words_by_length[23]])  # hope I got 
that right

will not return True?

Frank






More information about the Python-list mailing list