Comparison of Python dictionary traversal methods
#! /Usr/bin/pythonfrom time import clockl = [(x, x) for x in xrange (10000000)] d = dict (l) t0 = clock () # method 1 for I in d: n = d [I] t1 = clock () # Method 2: slowest for k, v in d. items (): n = vt2 = clock () # method 3: fastest, recommended for k, v in d. iteritems (): n = v t3 = clock () # Method 4 for k, v in zip (d. iterkeys (), d. itervalues (): n = v t4 = clock () print t1-t0, t2-t1, t3-t2, t4-t3
The above code is executed five times and the results are:
Root @ ubuntu :~ # Python test. py1.892906 11.893149 1.859164 3.45618root @ ubuntu :~ # Python test. py2.038906 11.808548 1.969358 3.498633root @ ubuntu :~ # Python test. py2.059066 11.473983 1.96166 3.695533root @ ubuntu :~ # Python test. py2.092667 11.372379 1.9519 3.656708root @ ubuntu :~ # Python test. py2.082951 12.910404 2.021785 3.663504
Visible, the fastest way is:
For k, v in d. iteritems ():...