Can I replace this for loop with a join?

Paul Rubin http
Mon Jun 22 03:26:51 EDT 2009


WP <no.i.dont at want.mail.from.spammers.com> writes:
> 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

Note that dict.keys() will return the keys in random order.

> but can I use a join instead?

  print '\n'.join('Press %s for %s' for (k,v) in sorted(dict.iteritems()))

(untested) should print them in order.  Yes it is ok to use %s to
format integers.

Note: normally you should not call your dictionary 'dict', since
'dict' is a built-in value and overriding it could confuse people
and/or code.



More information about the Python-list mailing list