String formatting using dictionaries

F

Fredrik Lundh

Clodoaldo said:
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']?:
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)
>>> d = {"list": [0, 1]}
>>> d = mapper(d)
>>> '%(list)s' % d [0, 1]
>>> '%(list[0])s' % d
0

</F>
 
P

Peter Otten

Clodoaldo said:
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']?:
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:
.... 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,511
Members
48,196
Latest member
NevilleFer

Latest Threads

Top