String formatting with two dictionaries?

piet at cs.uu.nl piet at cs.uu.nl
Mon Oct 8 06:23:41 EDT 2001


>>>>> Carsten Gaebler <clpy at snakefarm.org> (CG) writes:

CG> Hi there!
CG> Given a string

CG> s = "%(foo)s %(spam)s"

CG> and two dictionaries

CG> d1 = {"foo": "bar"}
CG> d2 = {"spam": "eggs"}

CG> how would you apply d1 and d2 to s without modifying or explicitly
CG> copying one of the dicts? I mean, I don't like to

CG> d3 = dictionary(d1)
CG> d3.update(d2)
CG> s = s % d3

class DictSet:
    def __init__(self, *dicts):
        self.dicts = dicts

    def __getitem__(self, attr):
        for d in self.dicts:
            if d.has_key(attr):
                return d[attr]
        raise KeyError, attr

s = "%(foo)s %(spam)s"

d1 = {"foo": "bar"}
d2 = {"spam": "eggs"}

print s % DictSet(d1,d2)
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



More information about the Python-list mailing list