NEWBIE: Extending a For Statement.

mosscliffe mcl.office at googlemail.com
Mon May 21 10:13:27 EDT 2007


On 21 May, 14:13, Larry Bates <larry.ba... at websafe.com> wrote:
> mosscliffe wrote:
> > I keep seeing examples of statements where it seems conditionals are
> > appended to a for statement, but I do not understand them.
>
> > I would like to use one in the following scenario.
>
> > I have a dictionary of
>
> > mydict = { 1: 500, 2:700, 3: 800, 60: 456, 62: 543, 58: 6789}
>
> > for key in mydict:
> >      if key in xrange (60,69) or key == 3:
> >            print key,mydict[key]
>
> > I would like to have the 'if' statement as part of the 'for'
> > statement.
>
> > I realise it is purely cosmetic, but it would help me understand
> > python syntax a little better.
Thank you all - it is all helping to expand my python knowledge.

I appreciate your comment about sticking with the simple format.

I am finding 'python', one of the most straightforward languages to
learn, yet very powerful in its capabilities.  The whole list concept,
is so akin to programming tasks, that it means I can think more about
design, than worrying about how to store and access data.

Richard

>
> > Thanks
>
> > Richard
>
> I find something like the following easy to read and easy to
> extend the contents of searchkeys in the future.
>
> searchkeys=range(60, 69) + [3]
> goodlist=[(k, v) for k, v in mydict.items() if k in searchkeys]
> for key, value in goodlist:
> print k,v
>
> -Larry





More information about the Python-list mailing list