[Tutor] Iterating over nested lists part2
Luis N
tegmine at gmail.com
Sun Jul 3 09:29:03 CEST 2005
On 7/2/05, Kent Johnson <kent37 at tds.net> wrote:
>
> Luis N wrote:
> > def listItems():
> > l= []
> > d = {}
> > for r in range(len(vw)):
> > for x in range(lt):
> > ed = desc[x]
> > exec("d['%s']=vw[%d].%s" % (ed,r,ed))
> > l.append(d)
> > print l
>
> If I understand correctly, you want to take all the rows of the view and
> turn them into dicts, and build a list of all the dicts. If so, the code
> above is way too complex.
>
> First, you can iterate over a list such as vw directly, you don't have to
> iterate the indices. Instead of
> for r in range(len(vw)):
> do something with vw[r]
>
> you just say
> for vwitem in vw:
> do something with vw
>
> Next, instead of exec you should use getattr(). To put the value into d
> you don't need either; you can assign to d[ed] directly. To get the 'ed'
> attribute from vwitem, use getattr(vwitem, ed).
>
> I also moved the assignment to d inside the loop so you start each row
> with a fresh dictionary. Here is the result:
>
> def listItems():
> l= []
> for vwitem in vw:
> d = {}
> for ed in desc:
> d[ed] = getattr(vwitem, ed)
> l.append(d)
> print l
>
> Kent
That's beautiful. I'm really grokking getattr, and I notice that it has some
close relations in the family of built-in functions.
Luis N.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050703/9e3762c6/attachment.htm
More information about the Tutor
mailing list