Printing formatted strings from a dictionary

Sean Berry sean_berry at cox.net
Wed May 12 16:51:49 EDT 2004


>>> 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" <tkpmep at hotmail.com> wrote in message
news:b4a8ffb6.0405121230.a564636 at posting.google.com...
> 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





More information about the Python-list mailing list