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

Ben Markwell benmarkwell at gmail.com
Sat Jan 28 06:47:25 CET 2006

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

Thank you Bob.  This is much to think about.  I very much appreciate your
concise explanation.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060128/9406a5ca/attachment.html 

More information about the Tutor mailing list