[Tutor] Reading file and storing keys

Dave Angel d at davea.name
Thu Jun 28 02:33:56 CEST 2012


On 06/27/2012 08:19 PM, moheem ilyas wrote:
> I am working on a problem from a book, Think Python, which I thought would
> be fairly easy. The problem is:
>
> Exercise 11.1. Write a function that reads the words in words.txt and
> stores them as keys in a
> dictionary. It doesn’t matter what the values are. Then you can use the in
> operator as a fast way to
> check whether a string is in the dictionary.
>
> Note: words.txt is just a huge word list file if anyone is confused about
> that
>
> Here is my failed solution:
>
> def tester():
>     fin = open('/home/moheem/Documents/words.txt', 'r')
>     value = 0
>     wordDict = dict()
>     for word in fin:
>         wordDict[word] = value
>         value = value + 1
>
>     fin.close()
>
> There seems to be a logical error. That is, when I check a key, i.e. one of
> the words from the file, is in the dictionary, I get false. (To check, I
> use: 'aa' in wordDict). I think the problem is that the key does not
> actually get placed in the dictionary, but the question is why?
>
>

Somehow you're thinking that the file consists only of words, and that
the for loop you've got will give you those words one at a time. It doesn't.

When you loop on a file that way, the lines each end in a newline
character, so you've got to strip them off before using them as keys.

for word in fin:
word = word.rstrip()
wordDict[word] = value
value += 1

You could have discovered this by simply printing out wordDict





-- 

DaveA



More information about the Tutor mailing list