[Tutor] Iterating over nested lists part2

Kent Johnson kent37 at tds.net
Sun Jul 3 04:49:53 CEST 2005

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)
    print l


More information about the Tutor mailing list