Making a dict from two lists/tuples
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu May 24 10:23:53 EDT 2001
"Emile van Sebille" <emile at fenx.com> wrote in
news:9ej1bl$36fcc$1 at ID-11957.news.dfncis.de:
> The
> technique of iterating through the indexes (i.e. for i in
> range(len(keys)): d1[keys[i]] = vals[i]) is clearer, and is still about
> 2 1/2 times faster than using zip.
>
This is a great way to demonstrate just how unreliable are sweepng
statements about how slow or fast some code 'should' be.
I added the for loop variant suggested by Emile onto Alex's timing code and
sure enough for range(10000) the for loop was 2.4 times faster and the map
3.5 times faster than the zip version. BUT, this code is unrealistic for a
variety of reasons:
The first variant gets a performance boost because the dictionary it
creates is destroyed inside the next timing loop!
Using global variables is unrealistic and slows the different loops up by
different amounts.
Initialising the dictionary outside the timing loops and putting the code
into a function speeds up all three loops so that 'fancy' is now only 3.4
times faster and forloop 3.0 times faster. Using xrange instead of range
makes forloop about 3.5 times faster than the plain zip version and
therefore slightly better than the map version. (These figures all
fluctuate, but on my machine the for loop/xrange variant wins about 3 times
out of every 4).
Take a different machine, different input lists, or different phase of the
moon and I'm sure the figures will be different again.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list