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

bonono at gmail.com bonono at gmail.com
Wed Nov 23 23:10:04 EST 2005


jep... at unpythonic.net wrote:
> One reason might be Practicality.  The zip() versions handily beat the
> listcomp versions on a 10kitem dict. (python2.4)
>
> $ timeit.py -s 'd = dict.fromkeys(range(10000))' '[(v, k) for (k, v) in d.iteritems()]'
> 100 loops, best of 3: 5.05 msec per loop
> $ timeit.py -s 'd = dict.fromkeys(range(10000))' '[(v, k) for (k, v) in d.items()]'
> 100 loops, best of 3: 7.14 msec per loop
> $ timeit.py -s 'd = dict.fromkeys(range(10000))' 'zip(d.itervalues(), d.iterkeys())'
> 100 loops, best of 3: 3.13 msec per loop
> $ timeit.py -s 'd = dict.fromkeys(range(10000))' 'zip(d.values(), d.keys())'
> 100 loops, best of 3: 3.28 msec per loop
>
> For comparison,
> $ timeit.py -s 'd = dict.fromkeys(range(10000))' 'd.items()'
> 100 loops, best of 3: 2.19 msec per loop
>
> Maybe there are also other reasons to promise this property that I'm not
> aware of.  Certainly it seems like this property is useful and not hard
> to provide for "non-perverse" implementations, much like the
Thanks, but we don't need the list comprehension(or do we) ? As the
return of d.iteritems() is already a list of tuples.

> now-documented stability of sort().
> 
> Jeff




More information about the Python-list mailing list