dict.get and str.xsplit

marek.rocki at wp.pl marek.rocki at wp.pl
Tue Feb 26 10:03:41 EST 2008


bearophileH... at lycos.com napisał(a):
> It's slower still, despite doing the lookup two times half of the
> times (half keys are present in the test set). The "in" is an
> operator, it's faster than a method call, but I don't understand the
> other details. Now the difference between 1.78 and 1.56 is small
> enough, so probably now it's not much noticeable in practice in real
> programs, so my original argument is mostly dead now :-) In the code
> points where speed matters instead of a single line with a get() I can
> use two lines to create a local adict_get.

AFAIK, method/function call is generally slow in Python (similarly to
the dot attribute lookup). As for the original prooblem, why not use
defaultdict? I think it's the most idiomatic way to achieve what we
want. And also the fastest one, according to my quick-and-dirty tests:

from collections import defaultdict

def main(N, M):

    # <snip>

    addict = defaultdict(lambda: None, adict)
    t = clock()
    for _ in xrange(M):
        for k in keys1:
            r = addict[k]
        for k in keys2:
            r = addict[k]
    print round(clock() - t, 2), "s"

adict.get: 3.12 s
adict_get: 2.24 s
in: 1.62 s
defaultdict: 1.05 s



More information about the Python-list mailing list