[Tutor] Reading file and storing keys

Alan Gauld alan.gauld at btinternet.com
Thu Jun 28 10:39:48 CEST 2012


On 28/06/12 01:19, moheem ilyas wrote:

> 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.

Notice that you do not return the dictionary.
So when the function completes the dictionary gets thrown away.
You probably need a line like

return wordDict

at the end of the function.

Then when you call tester assign the result to a variable:

words = tester()

> 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?

Then you can use

'aa' in words

But the other advice about stripping the newlines still applies too!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list