String formatting using dictionaries

Peter Otten __peter__ at web.de
Sat Apr 22 09:41: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]'

No, but you can provide a modified dictionary to get the effect:

>>> class Dict(dict):
...     def __getitem__(self, key):
...             if key in self:
...                     return super(Dict, self).__getitem__(key)
...             return eval(key, self)
...
>>> d = Dict(list=[0, 1])
>>> "%(list)s" % d
'[0, 1]'
>>> "%(list[0])s" % d
'0'
>>> "%(list[1]+42)s" % d
'43'

Peter



More information about the Python-list mailing list