> I'd say not clear, for two reasons. One is that I pretty much never
> use keys() in a for loop, I just use the dictionary.

Ok. Consider items() then. Again, I claim that the common use of
items() is to iterate over it.

,keys() should clearly behave the same as .items().

>> Applications that take a snapshot of the .keys() are rare (right?).
> 
> And the second is that I don't think it's rare to want to process the
> keys in sorted order. It's  not exactly common, but
> 
> keys = mydict.keys()
> keys.sort()
> for key in keys:

That is indeed a frequent case in 2.x. Fortunately, it is what David
calls "loud" breakage:

py> keys = mydict.keys()
py> keys.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict_keys' object has no attribute 'sort'

> In fact, the 2.5 standard library turns up 3 occurrences of
> "keys.sort". Given that that's just the ones that used the obvious
> name for the list to be sorted
> 
> Nowdays, I tend to write
> 
> keys = sorted(mydict.keys())   # Yeah, I know, .keys() is redundant...
> for key in keys:
> 
> or maybe
> 
> for key in sorted(mydict):
> 
> both of which are probably slower than the original version unless
> sorted switches to an insertion sort if passed a generator.

Notice that this isn't affected by the "spookiness" of dict.keys()
at all - it just works fine.

Why do you think this version is slower? It behaves exactly the
same as the original code: a list is created with all the keys,
and then that list is sorted, with the list-sort algorithm.

> I'd say the most direct name is to use the dictionary as an iterator
> directly. So if you don't think about it the way I don't think about
> it, you get the right thing in 2.x and 3.0.

Not in 2.0 - you couldn't iterate over a dictionary there.

Also, I claim that it is *not* obvious that iterating over a dictionary
iterates over the keys. It's a useful convention, but not obvious.
I recall having had to look it up for about a year or so until I
memorized it. Explicit is better than implicit, at least if you aim
for obviousness.

In any case, it's also common to use .items(), which you have to use
explicitly, and there the most common use is to iterate over it.
(the subject of this thread was about .items(), anyway)

Regards,
Martin
_______________________________________________
Python-3000 mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to