Printing formatted strings from a dictionary

Discussion in 'Python' started by Thomas Philips, May 12, 2004.

  1. 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?

    Thomas Philips
    Thomas Philips, May 12, 2004
    #1
    1. Advertising

  2. Thomas Philips

    Sean Berry Guest

    >>> d={'n1':1, 's1':'spam', 'n2':4}
    >>> x = "%s %s %s you" %(d['n1'], d['s1'], d['n2'])
    >>> x

    '1 spam 4 you'
    >>>



    "Thomas Philips" <> wrote in message
    news:...
    > 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?
    >
    > Thomas Philips
    Sean Berry, May 12, 2004
    #2
    1. Advertising

  3. (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

    --
    A difference which makes no difference is no difference at all.
    -- William James (I think. Reference anyone?)
    Michael Hudson, May 13, 2004
    #3
  4. Thomas Philips

    Peter Abel Guest

    Michael Hudson <> wrote in message news:<>...
    > (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
    Peter Abel, May 13, 2004
    #4
  5. [snip good reply from Peter]

    The other thing to remember is that there are implicit quotes:
    >>> d = {1:2}
    >>> "%(1)i"%d

    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    KeyError: 1
    >>> "%(1)i"%d

    '2'

    - Josiah
    Josiah Carlson, May 19, 2004
    #5
  6. Thomas Philips

    Peter Abel Guest

    Josiah Carlson <> wrote in message news:<c8gfov$9j9$>...
    > [snip good reply from Peter]
    >
    > The other thing to remember is that there are implicit quotes:
    > >>> d = {1:2}
    > >>> "%(1)i"%d

    > Traceback (most recent call last):
    > File "<stdin>", line 1, in ?
    > KeyError: 1
    > >>> "%(1)i"%d

    > '2'


    Uuuaaah, I can't stop learning YOU(python). Couldn't verify
    the above example. Maybe some fault happened to you because the code
    which raised the KeyError and the successfull one are the same for me.
    But the following works:
    >>> d={'1':2} # Remark the quotmarks '1'
    >>> '%(1)i'%d

    '2'
    >>>


    I even would not have believed that this kind of formatting would work.
    But the more I think about it the more it becomes consequential and logical.
    - Peter -

    > - Josiah
    Peter Abel, May 20, 2004
    #6
  7. Thomas Philips

    Terry Reedy Guest

    "Peter Abel" <> wrote in message
    news:...
    > >>> d={'1':2} # Remark the quotmarks '1'
    > >>> '%(1)i'%d

    > '2'
    > I even would not have believed that this kind of formatting would work.
    > But the more I think about it the more it becomes consequential and

    logical.

    >From Lib Ref 2.3.6.2. String Formatting ...


    Mapping key (optional), consisting of a parenthesised sequence of
    characters (for example, somename)).

    Examples generally use names for the char sequence, but restricting the
    sequence to a name would require more work for less functionality. Since %
    works with unicode as well as byte strings, one can, I presume, interpolate
    with unicode keys as well.

    Terry J. Reedy
    Terry Reedy, May 21, 2004
    #7
  8. > Uuuaaah, I can't stop learning YOU(python). Couldn't verify
    > the above example. Maybe some fault happened to you because the code
    > which raised the KeyError and the successfull one are the same for me.
    > But the following works:
    >
    >>>>d={'1':2} # Remark the quotmarks '1'
    >>>>'%(1)i'%d

    >
    > '2'


    Right, I forgot to rebind d. My bad, but it is great that you figured
    it out.

    - Josiah
    Josiah Carlson, May 21, 2004
    #8
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Stuart Woodard

    Server-side Printing With Formatted Text

    Stuart Woodard, Aug 3, 2003, in forum: ASP .Net
    Replies:
    0
    Views:
    312
    Stuart Woodard
    Aug 3, 2003
  2. Clint MacDonald

    Borderless formatted Printing from ASP.NET

    Clint MacDonald, May 1, 2005, in forum: ASP .Net
    Replies:
    3
    Views:
    835
  3. babo
    Replies:
    9
    Views:
    3,766
    Roedy Green
    Nov 30, 2005
  4. Andy B
    Replies:
    4
    Views:
    7,659
  5. wang
    Replies:
    15
    Views:
    455
Loading...

Share This Page