Can I replace this for loop with a join?

Kushal Kumaran kushal.kumaran at gmail.com
Mon Apr 13 17:13:56 CEST 2009


On Mon, Apr 13, 2009 at 8:33 PM, WP
<no.i.dont at want.mail.from.spammers.com> wrote:
> Hello, I have dictionary {1:"astring", 2:"anotherstring", etc}
>
> I now want to print:
> "Press 1 for astring"
> "Press 2 for anotherstring" etc
>
> I could do it like this:
> dict = {1:'astring', 2:'anotherstring'}
> for key in dict.keys():
>    print 'Press %i for %s' % (key, dict[key])
>
> Press 1 for astring
> Press 2 for anotherstring
>
> but can I use a join instead?
>

Sure.  Look up list comprehensions and generator expressions in the docs.

'\n'.join('Press %i for %s' % (key, value) for (key, value) in
d.items()) will get you the entire string.  Whether this is better
than what you have done is a consideration I leave to you.

-- 
kushal



More information about the Python-list mailing list