Nested string substitutions

holger krekel pyth at devel.trillke.net
Fri Dec 20 20:55:38 EST 2002


Lulu of the Lotus-Eaters wrote:
> Mike Meyer <mwm at mired.org> wrote previously:
> |def expand(key, dct):
> |    previous = ""
> |    while previous != dct[key]:
> |        previous = dct[key]
> |        for old, new in dct.items():
> |            dct[key] = dct[key].replace(old, new)
> |    map(lambda x: expand(x, subs), subs.keys())
> 
> Yeah... this looks pretty nice.  I'll steal this version.  (but I
> changed the spelling to avoid the builtin 'dict' name).
> 
> Btw. Sorry to Holger Krekel.  My example used spaces to separate all the
> substitutable terms, and your solution relied on that.  But that isn't
> the case in my actual problem (my description obviously wasn't quite
> complete enough).  I could probably adapt your version to use
> '.replace()', but the change doesn't jump out at me.

Yip, it helps to have a specification of a problem :-)

>From what i gather the following "oneliner" fits:

def expand(d):
    while filter(lambda (n, v): d.__setitem__(n, 
        reduce(lambda x,k: x.replace(k, d[k]), d, v)
    ) or v!=d[n], d.items()): pass

Obviously we could make this more readable (and possibly
faster) by e.g.  extracting the inner replacing lambda. 

regards,

    holger




More information about the Python-list mailing list