On 1/27/06, Bob Gailer <[EMAIL PROTECTED]> wrote:
Bob Gailer wrote:
> Alan Gauld wrote:
>
>> 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
>> time.
>> (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
>> definition
>> 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
>> else:
>> currentKey = line
>> isDefinition = True
>>
>>
> Or you can use next():
>
> for line in f:
> gloss[line] = f.next()
>
Or even:
[gloss.setdefault(l,f.next()) for l in f]
Hello Bob
I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] is beyond me at this point.
Thanks for your input.
Ben
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor