Why is dictionary.keys() a list and not a set?
Fredrik Lundh
fredrik at pythonware.com
Thu Nov 24 03:54:36 EST 2005
bonono at gmail.com wrote:
> I know that is a single list of tuples, I mean that can be used as
> well.
>
> for k, _ in d.items(): print k
> for _, v in d.items(): print v
> for k in d.keys(): print k
> for v in d.values(): print v
>
> Would there be a noticeable performance difference ?
Sloppy use of print statements is a great way to produce misleading
benchmarks [1], since the time it takes to print lots of stuff tends to
overshadow the actual algorithm (for bonus points, print to a terminal
window, and use "time" to measure performance, so you get startup
times as well). If you don't necessarily want to print all the stuff, my
original assertion still holds:
"creating a list full of tuples just to pull them apart and throw
them all away isn't exactly the most efficient way to do things"
Consider a dictionary with one million items. The following operations
k = d.keys()
v = d.values()
creates two list objects, while
i = d.items()
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.
</F>
1) careful use of timeit and generator expressions is another one:
http://online.effbot.org/2005_01_01_archive.htm#20050125 (code)
http://online.effbot.org/2005_01_01_archive.htm#20050127 (explanation)
More information about the Python-list
mailing list