[Tutor] newbie question
Evert Rol
evert.rol at gmail.com
Mon Oct 15 17:44:21 CEST 2007
Hi Ram,
> Either of the following should do it:
>
> print string.join([menu_specials[val] for val in
> menu_specials], ', ')
> or
> print string.join([menu_specials[val] for val in
> menu_specials.keys()],
> ', ')
> or
> print string.join([menu_specials[val] for val in ["breakfast",
> "lunch",
> "dinner"] ], ', ')
In addition, you'll need a tuple as the print argument list below:
>> print "%s %s %s" % (menu_specials["breakfast"], menu_specials
["lunch"], menu_specials["dinner"])
Your one-argument print statement can actually be written as a one-
element tuple:
>> print "%s" % (menu_specials["breakfast"], )
With this, and if you want to use your formatted print statements
instead of the join, you could use something like
print "Specials: %s %s %s" % tuple(menu_specials.values())
which turns the output of menu_specials.values() (a list) into a
tuple. Disadvantage is that you'll need to know the number of values
in advance, for the number of '%s' in your format string
(alternatively, you could build up the format string in a loop
first). Note that values() bypasses the above list comprehensions
entirely.
hth,
Evert
> Hi all,
>
> I have just started learning to program and am working through the
> Beginning
> Python from Wrox.
>
> I am working through one of the examples in the books on
> dictionaries. Here
> is the example.
>
>>>> menu_specials = {"breakfast" : "sausage and eggs",
> ... "lunch" : "split pea soup and garlic bread",
> ... "dinner": "2 hot dogs and onion rings"}
>>>> print "%s" % menu_specials["breakfast"]
> sausage and eggs
>>>> print "%s" % menu_specials["lunch"]
> split pea soup and garlic bread
>>>> print "%s" % menu_specials["dinner"]
> 2 hot dogs and onion rings
>
> I am trying to print out the entire dictionary but am getting an
> error.
> print "%s %s %s" % menu_specials["breakfast", "lunch", "dinner"]
> Traceback (most recent call last):
> File "<input>", line 1, in <module>
> KeyError: ('breakfast', 'lunch', 'dinner')
>
> I also tried
> print "%s %s %s" % menu_specials["breakfast"], menu_specials["lunch"],
> menu_specials["dinner"]
> Traceback (most recent call last):
> File "<input>", line 1, in <module>
> TypeError: not enough arguments for format string
>
> What is the correct syntax to output breakfast, lunch and dinner
> with one
> command?
>
> thanks,
>
> Ram
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list