Keeping track of things with dictionaries

Chris Angelico rosuav at gmail.com
Tue Apr 8 04:35:02 EDT 2014


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.

Also, there's a technical bug [1] in that I ought to use 'with' to
ensure that the file's properly closed. But for a simple example,
that's not critical.

ChrisA

[1] As Julia Jellicoe pointed out, it's an awful thing to be haunted
by a technical bug!



More information about the Python-list mailing list