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>
--
http://mail.python.org/mailman/listinfo/python-list