#!/usr/bin/python fromTimeImportClockl = [(x,x) forXinchXrange (10000000)] D = dict (l) t0 = Clock ()# Method One forIinchD:n = D[I]T1 = Clock ()# Method Two: Slowest forKvinchD.items (): n = vt2 = Clock ()# Method Three: Fastest, recommended method forKvinchD.iteritems (): n = v t3 = Clock ()# method Four forKvinchZip (D.iterkeys (), D.itervalues ()): n = v T4 = Clock ()PrintT1-t0, T2-t1, T3-t2, T4-T3
The above code executes five times, 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 quickest way is:
forin d.iteritems(): ...
Four ways to compare Python traversal dictionaries