Printing formatted strings from a dictionary

Peter Abel PeterAbel at gmx.net
Thu May 13 15:44:00 EDT 2004


Michael Hudson <mwh at python.net> wrote in message news:<m3r7toh75g.fsf at pc150.maths.bris.ac.uk>...
> tkpmep at hotmail.com (Thomas Philips) writes:
> 
> > I want to print "1 spam 4 you" using a formatted string that gets its 
> > inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so,
> > I write
> > 
> > >>> x="%('n1')d %('s1')s %('n2')d you"
> > >>> x % d
> > 
> > Traceback (most recent call last):
> >   File "<pyshell#22>", line 1, in -toplevel-
> >     x % d
> > KeyError: "'n1'"
> > >>> 
> > 
> > However, I get what I want if I edit x to remove the quotes around n1,
> > s1 and n2 and write
> > >>> x="%(n1)d %(s1)s %(n2)d you"
> > >>> x % d
> > '1 spam 4 you'
> > 
> > The syntax that works seems to run counter to the way dictionaries
> > work:
> > >>> d['n1']
>  1
> > >>> d[n1]
> > 
> > Traceback (most recent call last):
> >   File "<pyshell#18>", line 1, in -toplevel-
> >     d[n1]
> > NameError: name 'n1' is not defined
> > 
> > What is the error in my logic?
> 
> Um.  If the n1 is already inside a string literal, adding more quotes
> would be redundant?
> 
> CHeers,
> mwh

In Python every variable is hold in a dictionary where the key
is a string with the variable's name and the value is the object
where the variable is bound to.
The dictionary which holds the global variables is globals()
the dictionary for the local variables is locals() and the
dictionary for instances-attributes is instance.__dict__.
And always the key of the dictionary is a string. But when
you play around with a variable you address it by its name not
by a string.
So the following is equivalent:

>>> x=1
>>> globals()['x']=2

As you see:

>>> x
2
>>> x=4
>>> globals()['x']
4
>>> 

The same is in the following example:

>>> class A:
... 	def __init__(self):
... 		self.a=1
... 		self.b=2
... 		
>>> x=A()
>>> x.a
1
>>> x.b
2

Addressing x.a and x.b by dictionary:

>>> x.__dict__['a']
1
>>> x.__dict__['b']
2
>>> 

And back to your problem. Though the keys in the dictionaries are strings
you can address them by their names even if it is a self-made dictionary
and the same way you have to do in dictionary-formatting.

>>> y=999
>>> s='foo'
>>> print '%(s)s = %(y)d' % globals()
foo = 999
>>> 

Or

>>> print 'x.a=%(a)d x.b=%(b)d' % x.__dict__
x.a=1 x.b=2
>>> 

Regards
Peter



More information about the Python-list mailing list