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

Bob Gailer bgailer at alum.rpi.edu
Sat Jan 28 05:17:55 CET 2006


Ben Markwell wrote:
>
>
> On 1/27/06, *Bob Gailer* <bgailer at alum.rpi.edu 
> <mailto:bgailer at alum.rpi.edu>> 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.
[expr for l in f] is a "list comprehension". expr is an expression that 
may involve l.

result = [expr for l in f] # is equivalent to:

result = []
for l in f:
    result.append(expr)

"list comprehension" (once understood) is often easier to read and more 
efficient than the for loop.

result = xxx.setdefault(key, newvalue) is a dictionary method that tries 
to get an item from the dictionary xxx using key. If the key is not in 
the dictionary it adds the item assigning it newvalue. Equivalent to:

if key not in xxx:
    xxx[key] = newvalue
result = xxx[key]

Note that list comprehension and setdefault both return something. In my 
code the returned values are ignored. The outcome (populating a 
dictionary via a loop) is a "side effect".


More information about the Tutor mailing list