[Python-3000] Spooky behavior of dict.items() and friends

Mike Klaas mike.klaas at gmail.com
Thu Apr 3 00:08:53 CEST 2008


On 2-Apr-08, at 2:59 PM, Martin v. Löwis wrote:
> Jason Orendorff wrote:
>> On Tue, Apr 1, 2008 at 9:37 PM, "Martin v. Löwis"  
>> <martin at v.loewis.de> wrote:
>>> I think it's fairly obvious why the 2.x .keys() has to change. It's
>>> just too wasteful to actually build the list of all keys of a  
>>> dictionary
>>> (or even of all values, as you have to create all the tuples as  
>>> well),
>>> if all you want to do is to iterate over it, and the most common
>>> operation of .keys() is to iterate over it in a for look (right?).
>>
>> I don't think so.  Is this a use case for d.keys()?  Why not just
>> write "for k in d"?
>
> See the subject. What do you say about d.items()?

Exactly.  Iterating over the items of a dictionary is one of the most  
common dict operations, especially in list/genexp contexts.

$ pygrep '\.items' | wc -l
     128
$ pygrep '\.iteritems' | wc -l
     211

This may make it seem like iteration is only twice as common, but the  
majority of .items() use is in for loops where iteration is more  
appropriate.  There are only 46 non-'for' uses of .items() in this  
codebase:

$ pygrep '\.items' | grep -v for | wc -l
46

...and the majority of these cases would work fine with views (input  
to sorted(), etc).  Needing a physical list snapshot of them items  
that will be used independently of the dictionary is a much rarer use  
case.  It is good that this will be distinguished from the iteration  
use-cases with the extra syntax list(d.items()).

-Mike




More information about the Python-3000 mailing list