Why is dictionary.keys() a list and not a set?

Fredrik Lundh fredrik at pythonware.com
Thu Nov 24 05:07:07 EST 2005


bonono at gmail.com wrote:

> > creates just over one million objects.  In your "equivalent" example,
> > you're calling d.items() twice to produce two million objects, none
> > of which you really care about.
>
> This is what I get from the doc :
> a.items()  a copy of a's list of (key, value) pairs  (3)
> a.keys() a copy of a's list of keys (3)
> a.values() a copy of a's list of values
>
> I can't derive what you mean by "two list objects" vs "million
> objects".

The "copy of a's list of" is a list object.

The "pairs" are tuples, which are objects too.  For a dictionary with
one million items, the "items" method has to create one million "pair"
tuples before it can return them to you...  (the difference between
"items" and "iteritems" is that the latter doesn't create all of them
up front; it still has to create them, though).

In Python, everything that you can put in a variable or otherwise save
for a later time is an object.  All objects must be created.  Creating a
new object is often very cheap, but the cost is never zero.

</F>






More information about the Python-list mailing list