News for hackers. Stuff that matters.
Re:Try/Except vs. If in Dictionary Key Access Python Perform... by carapace on Saturday April 28, 2018 @11:59AM (#16948229)
Use try..except.. when you expect it to mostly succeed.

    $ python -m timeit -s "a={k:k  for k in range(10000)}" 'try:
       b=a[10001]
    except:
       pass'
    1000000 loops, best of 3: 0.276 usec per loop

    $ python -m timeit -s "a={k:k  for k in range(10000)}" 'try:
       b=a[1]    
    except:
       pass'
    10000000 loops, best of 3: 0.0255 usec per loop

"try" is fast, "except" is slow
Re:Try/Except vs. If in Dictionary Key Access Python Perform... by ilhicas on Saturday April 28, 2018 @12:29PM (#16948355)
Thanks for the input, yes I've since read that the problem lies on the exception catch, and definitely the time toll is in it.
Re:Try/Except vs. If in Dictionary Key Access Python Perform... by carapace on Saturday April 28, 2018 @12:03PM (#16948247)
However...

    $ python -m timeit -s "a={k:k  for k in range(10000)}" 'if 10001 in a:
       b=a[10001]
    else:
       pass'
    100000000 loops, best of 3: 0.0187 usec per loop
I gotta say, I didn't expect that. I thought the try..except.. for keys in the dict would be faster than this form. TIL