473,385 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 1012
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Thomas Philips | last post by:
Consider the following simple dictionary e={1:'one', 2: 'two'} e >>>'one' However, If I attempt to print e using a formatted string print " %(1)s" %e, I get a KeyError: '1'
8
by: Michele Simionato | last post by:
I was playing with string.Template in Python 2.4 and I came out with the following recipe: import sys from string import Template def merge(*dictionaries): """Merge from right (i.e. the...
8
by: Filip Dreger | last post by:
Each function has a func_code property that is suposed to contain the pure bytecode of the function. All the context (including reference to relevant namespaces) is stored in different fields of...
10
by: Oliver S. | last post by:
I've developed a string-class that holds the string in an array which is a member-variable of the class and that has maximum-size which is con- figurable through a template-parameter. If any...
5
by: Murali | last post by:
In Python, dictionaries can have any hashable value as a string. In particular I can say d = {} d = "Right" d = "Wrong" d = "test" In order to print "test" using % substitution I can say
7
by: L. Scott M. | last post by:
Have a quick simple question: dim x as string x = "1234567890" ------------------------------------------------------- VB 6 dim y as string
5
by: linnorm | last post by:
I've got a bit of code which has a dictionary nested within another dictionary. I'm trying to print out specific values from the inner dict in a formatted string and I'm running into a roadblock. ...
3
by: Rich Shepard | last post by:
I need to learn how to process a byte stream from a form reader where each pair of bytes has meaning according to lookup dictionaries, then use the values to build an array of rows inserted into a...
14
by: Scott M. | last post by:
Ok, this is driving me nuts... I am using VS.NET 2003 and trying to take an item out of a row in a loosely-typed dataset and place it in a label as a currency. As it is now, I am getting my...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.