Python 3: dict & dict.keys()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jul 25 01:52:50 EDT 2013


On Wed, 24 Jul 2013 13:17:12 -0400, Terry Reedy wrote:

> On 7/24/2013 12:34 PM, Chris Angelico wrote:
> 
>> Side point: Why is iterating over a dict equivalent to .keys() rather
>> than .items()? It feels odd that, with both options viable, the
>> implicit version iterates over half the dict instead of all of it.
>> Obviously it can't be changed now, even if .items() were the better
>> choice, but I'm curious as to the reason for the decision.
> 
> Both were considered and I think there were and are two somewhat-linked
> practical reasons. First, iterating over keys in more common than
> iterating over items. The more common one should be the default.
> 
> Second, people ask much more often if 'key' is in dict than if 'key,
> value' is in dict. This is true as well for keyed reference books such
> as phone books, dictionaries, encyclopedias, and for the same reason.
> This is  coupled with the fact that the default meaning of 'item in
> collection' is that iterating over 'collection' eventually produces
> 'item' or a value equal to 'item'.

That second point was the deciding factor when direct iteration over 
dicts was added. has_key() was deprecated in favour of "key in dict", and 
that pretty much forced iteration to go over keys by default. The 
reasoning is, "x in y" ought to be equivalent to:

for tmp in y:
    if x == tmp: return True
return False

There's probably even a PEP about this, if anyone is less lazy/busy and 
can be bothered looking for it.


-- 
Steven



More information about the Python-list mailing list