Making a dict from two lists/tuples

s713221 at student.gu.edu.au s713221 at student.gu.edu.au
Fri May 25 14:16:55 EDT 2001


Well this is the first time that I've actually tried to time something.
Below is my code for some of the various methods mentioned in this
thread.

import time
def iterzipdict(keys,values):
    dict = {}
    for key, value in zip(keys,values):
        dict[key] = value
    return dict

def itermapdict(keys,values):
    dict = {}
    for key, value in map(None, keys, values):
        dict[key] = value
    return dict

def nonitermapdict(keys,values):
    dict = {}
    map(dict.setdefault,keys,values)
    return dict

def iterolddict(keys,values):
    dict = {}
    for i in range(len(keys)):
        dict[keys[i]] = values[i]
    return


def tester(func, keys,values):
    oldtime = time.clock()
    func(keys, values)
    return time.clock() - oldtime


    
if __name__ == '__main__':
    no_items = 100000
    keys = range(no_items)
    values = range(no_items)
    print "iterzipdict took %s seconds." % repr(tester(iterzipdict,
keys,values))
    print "itermapdict took %s seconds." % repr(tester(itermapdict,
keys,values))
    print "nonitermapdict took %s seconds." %
repr(tester(nonitermapdict, keys,values))
    print "iterolddict took %s seconds." % repr(tester(iterolddict,
keys,values)

And here are three runs on a Mandrake 7.2 Linux AMD 450 KHz machine.

[joal at bb408 joal]$ python2 timer.py
iterzipdict took 1.75 seconds.
itermapdict took 1.47 seconds.
nonitermapdict took 0.49000000000000021 seconds.
iterolddict took 0.56000000000000005 seconds.
[joal at bb408 joal]$ python2 timer.py
iterzipdict took 1.7399999999999998 seconds.
itermapdict took 1.4300000000000002 seconds.
nonitermapdict took 0.54000000000000004 seconds.
iterolddict took 0.55000000000000027 seconds.
[joal at bb408 joal]$ python2 timer.py
iterzipdict took 1.7399999999999998 seconds.
itermapdict took 1.46 seconds.
nonitermapdict took 0.54000000000000004 seconds.
iterolddict took 0.5600000000000005 seconds.
[joal at bb408 joal]$

I was wondering, the first and second methods are three times the speed.
Would this have to do with the time taken by zip and map to create a new
list? Nonitermap and iterold just go ahead and make the dictionary. Was
wondering if I had come to the right conclusion?

Joal Heagney/AncientHart



More information about the Python-list mailing list