How much slower is dict indexing vs. list indexing?

skip at skip at
Fri Jan 12 15:31:18 CET 2007

    Emin> It sounds like it's probably not worth the effort in general, but
    Emin> might be for extremely ultra-critical parts of code.

Even in extremely ultra-critical parts of code I doubt the loss of
readability would be worth it.  If there are situations where you can really
gain by switching from a natural indexing scheme to lists, there are
probably other places in your code where you will gain just as much benefit
without the corresponding loss of readability.  Indexing lists only appears
to be about twice as fast as indexing dicts:

    % -s "data = {'a' : 1, 'b' :2, 'c' : 3}" "for k in 'abc': x = data[k]"
    100000 loops, best of 3: 4.61 usec per loop
    % -s "data = [1, 2, 3]" "for k in [0, 1, 2]: x = data[k]"
    100000 loops, best of 3: 2.97 usec per loop

If you're worried about regaining a couple microseconds per index you
probably shouldn't be using Python.


More information about the Python-list mailing list