[Tutor] newbie question

Trilok Khairnar trilokgk at gmail.com
Mon Oct 15 17:59:29 CEST 2007


Thinking more about the solutions I posted, I have a couple of questions :-)

1]    print string.join([menu_specials[val] for val in menu_specials], ', ')

>> Will this use iterkeys() under the hood?
2]    print string.join([menu_specials[val] for val in
menu_specials.keys()], ', ')
>> Given that a.keys() returns a "copy" of a's list of keys, will it be
memory intensive for large lists and it's better to use an iterator?

Thanks,
Trilok.

-----Original Message-----
From: Trilok Khairnar [mailto:trilokgk at gmail.com]
Sent: Monday, October 15, 2007 9:05 PM
To: 'Ramkumar Kashyap'
Cc: 'tutor at python.org'
Subject: RE: [Tutor] newbie question

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"]  ], ', ')

Thanks,
Trilok.

________________________________

From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Ramkumar Kashyap
Sent: Monday, October 15, 2007 8:32 PM
To: tutor at python.org
Subject: [Tutor] newbie question


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








More information about the Tutor mailing list