Newbie Questions: Swithing from Perl to Python
Roy Smith
roy at panix.com
Sun Oct 26 08:47:44 EST 2003
In article <pan.2003.10.26.04.24.12.305521.55687 at tampabay.rr.com>,
Todd Stephens <huzzah at tampabay.rr.com> wrote:
> 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)
> myL.sort()
> for x in myL:
> print "%s = %s" %(x, myD[x])
>
> When run, it yields this:
> e = 1
> k = 2
> r = 3
> x = 4
>
> 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
> doesn't care?
The ability to pass a dictionary to list() is relatively new (i.e. "I
didn't even know you could do that and had to go look it up"), and
depends on a change to dictionaries which make them iterable. If I
follow the historical notes correctly, this change happened in Python
2.2, which at this point I guess is about two years old (as you get
older, your definition of "relatively new" changes :-))
My personal opinion is that
keys = myDict.keys()
is more readable than
keys = list(myDict)
but the two end up with exactly the same result. I prefer the keys()
version because it makes it more explicit whether you're getting the
keys or the values. With the latter, the only hint is the naming of the
variable used to store the new list. Doing
myList = list(myDict)
would leave me scrambling for the documentation because I wouldn't have
a clue which it was.
More information about the Python-list
mailing list