[Tutor] Trying to enter text from a file to a Dictionary

Alan Gauld alan.gauld at freenet.co.uk
Fri Jan 27 11:01:19 CET 2006

Hi Ben,

> I want to enter the words and definitions from the  text file into the 
> dict.
> The way the text file is set up is that one  line is the word and the
> next line is the definition.

>  I tried using a for loop like this
>  f = open('glossary.txt','r')
>  gloss = {}
>  for line in f:
>      gloss[line] = line

The problem that you have is that you really need to read two lines at a 
(Assuming that the definitions are all on one line which may not be true!)
A while loop may be easier in this case.

A for loop will read each line individually. You then need to set a 
flag to tell the loop body whether you are reading a definition or a key.

Either type of loop is possible. Since you started with a for loop lets 
stick with it...

definition = False
currentKey = None

for line in f:
    if isDefinition:
       gloss[currentKey] = line
       currentKey = None
       isDefinition = False
       currentKey = line
       isDefinition = True

If the definitions take up more than one line each then you will need to 
about how to identify the end of a definition - a blank line maybe? You will
need to append the lines to the glossary entry (rather than just assign 
until the end of the definition. And you will need to update the 
flag at the appropriate times.


Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list