Python 3: dict & dict.keys()

Terry Reedy tjreedy at udel.edu
Wed Jul 24 13:17:12 EDT 2013


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'.

-- 
Terry Jan Reedy




More information about the Python-list mailing list