Is it possible to sort a dictionary?
Carel Fellinger
cfelling at iae.nl
Mon Mar 26 20:09:52 EST 2001
Alex Martelli <aleaxit at yahoo.com> wrote:
> Fine! Even faster & simpler:
Simpler yes, but faster? Are you sure? Lately I tested something
similar and was surprised when I found the dict.items function to be
soo slow that going through the whole dict indexing each entry
one by one was faster.
So let me benchmark again ( and please be gently when you tell me
were I fucked up this time :)
The result were with python 1.5.2:
tested t_items: 4.76
tested t_keys: 3.9
and with python 2.0 an even more dramatic advantage for dict.keys:
tested t_items: 4.6
tested t_keys: 2.72
And the code used was:
import time
dict = {}
for i in range(1000):
dict[i] = i
def test(f):
start = time.clock()
for i in range(1000):
f()
return time.clock() - start
def t_items(dict=dict):
items = dict.items()
items.sort()
for key, value in items:
v = value
def t_keys(dict=dict):
keys = dict.keys()
keys.sort()
for key in keys:
v = dict[key]
print 'tested t_items:', test(t_items)
print 'tested t_keys: ', test(t_keys)
--
groetjes, carel
More information about the Python-list
mailing list