Can I replace this for loop with a join?

Tim Chase python.list at tim.thechases.com
Mon Apr 13 11:19:23 EDT 2009


WP 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

Remember that a dict is inherently unordered, and if you get it 
ordered, you're just lucky :)  Also, it's bad style to mask the 
builtin "dict" with your own.

> but can I use a join instead?

If you want to lean on this ordered assumption, you can simply do

   d = {1:"astring", 2:"another string"}
   s = '\n'.join(
     "Press %i for %s" % pair
     for pair in d.iteritems()
     )

and you'd have the resulting value in "s".

But remember that if the order appears broken, you get to keep 
both parts :)  Better to do something like

   s = '\n'.join(
     "Press %i for %s" % pair
     for pair in sorted(d.items())
     )

-tkc











More information about the Python-list mailing list