[Python-3000] Default dict iterator should have been iteritems()

Nick Coghlan ncoghlan at gmail.com
Tue Sep 4 17:09:12 CEST 2007


Guido van Rossum wrote:
> On 9/4/07, Noam Raphael <noamraph at gmail.com> wrote:
>> On 9/4/07, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>>> Noam Raphael wrote:
>>>> The default dict iterator should in principle be iteritems(), and not
>>>> iterkeys().
>>> This was discussed at length back when "in" support was
>>> added to dicts. There were reasons for choosing to do it
>>> the way it's done, and I don't think it's likely to be
>>> changed.
>>>
>> Just out of curiousity - do you remember these reasons?
> 
> Consistency with "k in d", where you'll agree with me that the only
> useful interpretation is checking for a key. It would be annoying if
> "for x in obj:" no longer rhymed with "if x in obj:".

I would certainly be rather annoyed if the following code could blow up 
with an assertion error in the absence of any threading foolishness:

   for k in d:
       assert k in d

Containment and iteration really do need to be kept consistent and 
having the value matter when checking for dictionary containment would 
be outright bizarre. Put the two together and it makes sense for 
dictionary iteration and containment tests to both be based on keys.

Note that the other basic container types in the standard library 
(lists, tuples, sets, strings, xrange) also obey the 
iteration<->containment invariant above.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list