Pythonic infinite for loop?

Ryan Kelly ryan at rfk.id.au
Thu Apr 14 22:46:47 EDT 2011


On Fri, 2011-04-15 at 12:34 +1000, Ryan Kelly wrote:
> On Fri, 2011-04-15 at 12:10 +1000, Chris Angelico wrote:
> >
> > 
> > My first draft looks something like this. The input dictionary is
> > called dct, the output list is lst.
> > 
> > lst=[]
> > for i in xrange(1,10000000): # arbitrary top, don't like this
> >   try:
> >     lst.append(parse_kwdlist(dct["Keyword%d"%i]))
> >   except KeyError:
> >     break
> >
> It might be even easier to just iterate through the dictionary keys:
> 
>   for k in sorted(dct.keys()):
>       if k.startswith("Keyword"):
>           lst.append(parse_kwdlist(dct[k]))

Actually sorted() won't work here, since it sorts lexicographically.  So
you'd wind up with "Keyword111" before "Keyword2".  You would have to
sort after extracting the necessary info (assuming order is actually
important in the final list)


   Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-list/attachments/20110415/4d97a429/attachment.sig>


More information about the Python-list mailing list