Newbie Questions: Swithing from Perl to Python

John J. Lee jjl at pobox.com
Sun Oct 26 09:12:40 EST 2003


Todd Stephens <huzzah at tampabay.rr.com> writes:

> On Sat, 25 Oct 2003 23:16:35 -0400, Roy Smith wrote:
> 
> > Exactly.
> > 
> > keys = myDict.keys()
> > keys.sort()
> > for key in keys:
> >    print key
>  
> Thanks for the info.  Knowing that the Python community prefers one
> correct way to do something, can you explain to me how this is
> different/incorrect? :
> 
> myD = {'x':4, 'k':2, 'r':3, 'e':1}
> myL = list(myD)

That's perhaps slightly obscure, relying on the fact that a dict
supports the iterator protocol, providing an iterator over its keys.

 list( [sequence])

    Return a list whose items are the same and in the same order as
    sequence's items. sequence may be either a sequence, a container
    that supports iteration, or an iterator object. If sequence is
    ...

Of course, though the list builtin function respects order, a dict's
keys don't have any guaranteed ordering.

Using .keys() is more conventional and explicit, hence clearer.


> myL.sort()
> for x in myL:
>    print "%s = %s" %(x, myD[x])

This isn't Perl, everything is a 'my' variable unless you explictly
ask otherwise, so there's no need to restate that fact in your
variable names.  Having 'my' as a prefix to every name is bad style in
Python.

[...]
> I have tried this both ways, and I appear to get the same results.  Are
> there situations where the method I have listed here would yield
> unpredictable or unwanted results?  Or is this an area where Python

I think it's guaranteed to return the same results as using .keys().


John




More information about the Python-list mailing list