Can I replace this for loop with a join?

Nicolas Dandrimont Nicolas.Dandrimont at crans.org
Mon Apr 13 11:21:40 EDT 2009


* WP <no.i.dont at want.mail.from.spammers.com> [2009-04-13 17:03:17 +0200]:

> 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?
>
> Thanks for any replies!

First off, you shouldn't use 'dict' as a variable name, as it shadows
the built-in 'dict'.

If you really want to obfuscate this, you could use:

my_dict = {1: 'astring', 2: 'anotherstring'}
print "\n".join('Press %i for %s' % (key, value) for key, value in my_dict.items())

I find this highly ugly and non readable, though.

HTH,
-- 
Nicolas Dandrimont

"sic transit discus mundi"
(From the System Administrator's Guide, by Lars Wirzenius)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090413/9b985297/attachment-0001.sig>


More information about the Python-list mailing list