Access dictionary in order?

Emile van Sebille emile at fenx.com
Mon Jul 26 10:45:29 EDT 1999


Hi Diego,


Diego Dainese <ddainese97x at x18dsi.unive.it> wrote in message
news:slrn7po8t3.6k.diego at blanka2.blankanet.it...
> On Sun, 25 Jul 1999 12:22:03 -0500 (CDT), Skip Montanaro wrote:
> > You demonstrated the best way.  There is no need to save the key
list unless
> > the dictionary is very large though.  Just grab 'em and sort 'em
when you
> > need:
> >
> >     keylist = dict.keys()
> >     keylist.sort()
> >     for key in keylist: do_stuff(dict[key])
> >
>
> But how much time requires the keylist generation?

I tried this test and found that the results varied on the number of
items.  For example, at 100000 entries, the .keys() was generally
faster, but at 50000 entries, it was not faster.  I'm on a PII-266
w/64Mb but I've got lots running so YMMV (your mileage may vary).  Test
on your platform.  Ultimately, you'd need to wrap up a separate keylist
in a class structure to ensure consistency, and that may also impact
speed.

########
import time
d = {}
r = ('spam','eggs','eggs','bacon','eggs','and','spam')
test1start = time.clock()
for i in xrange(100000):
 d[i] = i, 2*i, r
k = d.keys()
test1end = test2start = time.clock()
d = {}
k = []
for i in xrange(50000):
 d[i] = i, 2*i, r
 k.append(i)
test2end = time.clock()
print 'test1: ',test1end - test1start
print 'test2: ',test2end - test2start
########
>
> That is, the keylist is made traversing all the dictionary nodes or is
> cached inside it?

I can't help you with this one...

>
> --
> Diego Dainese
> --
> To reply remove the numbers and the `x' from my address
> --
> Sorry for my bad English!

Not bad at all.

--

Emile van Sebille
emile at fenx.com
-------------------








More information about the Python-list mailing list