Iterating over a dictionary's sorted keys
Alan Daniels
daniels at mindspring.com
Thu May 25 23:18:03 EDT 2000
On 25 May 2000 08:56:38 GMT, Remco Gerlich
<scarblac-spamtrap at pino.selwerd.nl> wrote:
[snip...]
>Why the problem with multiple lines and an extra variable here and there?
Yes, but the short version reminds me very much of one of my favorite
python idioms:
lines = open("some_file", "rt").readlines()
Grabbing lines out of a (reasonably small) file is something I do
quite often, and I love the simplicity and elegance of doing it all in
a very readable and succinct one-liner. Admittedly, I could always go
this route:
f = open("some_file", "rt")
lines = []
line = f.readline()
while (line):
lines.append(line)
line = f.readline()
f.close()
But then that one-liner just became six-liner with two unneeded vars
left over. For that kind of wordiness, you may as well be writing in,
say, Java. :-)
The ability to do:
for k in blah.keys().sort():
print k
rather than:
keys = blah.keys()
keys.sort()
for k in keys:
print k
is only thwarted by the fact that the "sort()" method of a list
inexplicably returns a None. I truly wish that more methods returned a
reference to "self". After all, when you sort a list, don't you get a
new list, maybe not in implementation, but philisophically? Or when
you reverse it? Sure, its the same *object*, but its been changed. I
don't think returning a reference to itself would do any harm.
And then I could use one of the Java idioms I *do* like, the ability
to chain().method().calls().together() when they all operate on the
same object.
Java-Is-A-Harsh-Mistress'ly yours, Alan.
--
============================================================
Alan Daniels
daniels at mindspring.com
More information about the Python-list
mailing list