String formatting using dictionaries

Fredrik Lundh fredrik at pythonware.com
Sat Apr 22 09:18:30 EDT 2006


Clodoaldo Pinto wrote:

> I know how to format strings using a dictionary:
>
> >>> d = {'list':[0, 1]}
> >>> '%(list)s' % d
> '[0, 1]'
>
> Is it possible to reference an item in the list d['list']?:
>
> >>> '%(list[0])s' % d
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> KeyError: 'list[0]'

not directly, but you can wrap the dictionary in a custom mapper
class:

    class mapper(dict):
        def __getitem__(self, key):
            try:
                return dict.__getitem__(self, key)
            except KeyError:
                k, i = key.split("[")
                i = int(i[:-1])
                return dict.__getitem__(self, k)[i]

    >>> d = {"list": [0, 1]}
    >>> d = mapper(d)
    >>> '%(list)s' % d
    [0, 1]
    >>> '%(list[0])s' % d
    0

</F>






More information about the Python-list mailing list