Questions about nested for's vs map

Felix Thibault felixt at dicksonstreet.com
Fri Oct 22 22:25:39 EDT 1999


I've been working on a subclass of UserDict that uses code
like the code at the end of this post to build a list of dictionaries
that I can use for profiling the subclass. I use it like this:

>>> for a in build(( ('conspiracy', 'top-secret','covert-action'),
('black helicopters', 'area 51', 'mk-ultra') )): print a

I build this code...
dlist = []
for key0 in ('conspiracy', 'top-secret', 'covert-action'):
    for key1 in ('black helicopters', 'area 51', 'mk-ultra'):
        d= {key0: {key1: (key0,key1,)}}
        dlist.append(d)

and this is my output
{'conspiracy': {'black helicopters': ('conspiracy', 'black
helicopters')}}
{'conspiracy': {'area 51': ('conspiracy', 'area 51')}}
{'conspiracy': {'mk-ultra': ('conspiracy', 'mk-ultra')}}
{'top-secret': {'black helicopters': ('top-secret', 'black
helicopters')}}
{'top-secret': {'area 51': ('top-secret', 'area 51')}}
{'top-secret': {'mk-ultra': ('top-secret', 'mk-ultra')}}
{'covert-action': {'black helicopters': ('covert-action', 'black
helicopters')}}
{'covert-action': {'area 51': ('covert-action', 'area 51')}}
{'covert-action': {'mk-ultra': ('covert-action', 'mk-ultra')}}
>>> :)

I've been trying to move from building the arbitrarily deeply nested
for's to
something using map, but so far I haven't gotten it to work. Is there a
standard
way to do this, or another, better way to do the same thing ?

Thanks in advance,
Felix

build2.py-----------------------------------------------------

import string

def build(tupe, mode='dict'):
    """build(TupleOfSequences, [mode]) - this function iterates over
    each sequence inside iterations of the lefter sequences of the tuple
to
    build a list of dictionaries,If themode 'tupe' is passed in the
(un-nested)
    dictionaries are made with tuple keys.
    """
    initcodel = ['dlist = []\n']
    tab = '    '
    loopcodel = []
    depth = len(tupe)
    indexes = range(depth)
    indextupes = tuple(indexes)
    def makeloop(index, tupe=tupe, tab=tab):
        return tab*index+'for key'+`index`+' in '+`tupe[index]`+':\n'
    loopcodel = map(makeloop, indexes)
    assigncodel= [( tab*depth+'d= '+'{key%s: '*depth ) % indextupes]
    if mode == 'dict':
        assigncodel.append(( '('+'key%s,'*depth+')'+'}'*depth+'\n' )
                           % indextupes)
    elif mode == 'tupe':
        assigncodel.append( '('+'key%s,'*depth+')'+'}\n' % indextupes )
    codelist = initcodel+loopcodel+assigncodel
    codelist.append(tab*depth+'dlist.append(d)\n')
    codestring = string.join(codelist, '')
    print 'I build this code...'
    print codestring
    print 'and this is my output'
    exec(codestring)
    return dlist






More information about the Python-list mailing list