470,810 Members | 901 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,810 developers. It's quick & easy.

String formatting using dictionaries

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]'

Regards, Clodoaldo Pinto

Apr 22 '06 #1
3 970
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
Apr 22 '06 #2
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>

Apr 22 '06 #3
Thank you guys, you are great!

Apr 22 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Thomas Philips | last post: by
8 posts views Thread by Michele Simionato | last post: by
8 posts views Thread by Filip Dreger | last post: by
10 posts views Thread by Oliver S. | last post: by
5 posts views Thread by Murali | last post: by
7 posts views Thread by L. Scott M. | last post: by
5 posts views Thread by linnorm | last post: by
14 posts views Thread by Scott M. | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.