[Tutor] Question about formating string with dictionary

John Fouhy john at fouhy.net
Fri Apr 27 04:04:40 CEST 2007


On 27/04/07, Shuai Jiang (Runiteking1) <marshall.jiang at gmail.com> wrote:
> Hello everyone,
>
> The program that I am working on right now have a template for string
> formatting.
> My question is that is it possible to use multiple dictionary to format the
> string.
>
> For example
> x = {'foo':1234, 'bar': 5678}
> y = {'spam':'hello','cheese':'good-bye'}
>
> is there any way to use his pseudo code
> template = \
> """Foo = %(foo)s
> bar = %(bar)s
> spame = %(spam)s
> cheese = %(cheese)s"""
>
> print template %x,y

My best suggestion would be to write a function to combine multiple
dictionaries into one.  eg:

def combine(*dicts):
    """ Combine multiple dictionaries into one.  Rightmost
dictionaries have precedence. """
    res = {}
    for d in dicts:
        res.update(d)
    return res

Then:

x = {'foo':1234, 'bar': 5678}
y = {'spam':'hello','cheese':'good-bye'}

"""Foo = %(foo)s
bar = %(bar)s
spame = %(spam)s
cheese = %(cheese)s""" % combine(x, y)

HTH!

-- 
John.


More information about the Tutor mailing list