Fast method in order to get dict value

I am new for Python. In order to get dict value I used the code:
tbl = {‘aaa’:111, ‘bbb’:222, ‘ddd’:444}
vlx = None
if ‘ccc’ in tbl:
vlx = tbl[‘ccc’]
else:
vlx = ‘Unknown key: ccc’
print(vlx)

Is there a faster method for this code?

You can try tbl.get('ccc', 'Unknown key: ccc').

The fastest method will depend on whether or not the key ‘ccc’ is
present.

If the key is usually there, the fastest method is:

try:
    vlx = tbl['ccc']
except KeyError:
    vlx = 'Unknown key'

That’s as fast as possible, if the key is present, but it will be slow
if it is missing.

If the key is usually missing, then this will be faster:

if 'ccc' in tbl:
    vlx = tbl['ccc']
else:
    vlx = 'Unknown key'

but if the key is present it does twice as much work as needed.

Another alternative, probably slower than both of the others, is this:

vlx = tbl.get('ccc', 'Unknown key')

Don’t stress about “the fastest” method. All three methods will probably
be more than fast enough for what you are doing. And if not, you can
profile your program, find out where the slow parts are, and concentrate
on speeding up the slow parts.

Are these been benchmark some where?
I would be interested to adjust my understanding

Benchmarks will depend on your computer, the CPU, the amount of memory,
how large the dict is, which keys are used, the version of Python,
whether it is a debug build, etc.

Here is a quick example. At the OS terminal (not the Python prompt):

[steve ~]$ python3 -m timeit -s "d = dict.fromkeys(range(10000))" 
> "try: d[100]
> except KeyError: pass"
10000000 loops, best of 5: 32 nsec per loop
[steve ~]$ python3 -m timeit -s "d = dict.fromkeys(range(10000))" 
> "if 100 in d: d[100]"
5000000 loops, best of 5: 45.9 nsec per loop

See the timeit module for more information.

Nice - I was looking for the dict.get - I think it should perform better than the “if 100 in d” code…
Do you also have it handy - to share so it can be fart compare on the same environment ?

I used the following

from timeit import timeit

tbl = {'aaa': 111, 'bbb': 222, 'ddd': 444}

def ask_for_forgiveness():
    try:
        return tbl['ccc']
    except KeyError:
        return 'Unknown key'

def conditional():
    if 'ccc' in tbl:
        return tbl['ccc']
    else:
        return 'Unknown key'

def builtin():
    return tbl.get('ccc', 'Unknown key')

print('ask for forgiveness', timeit(ask_for_forgiveness))
print('conditional', timeit(conditional))
print('builtin', timeit(builtin))

and got

ask for forgiveness 0.17507593100890517
conditional 0.06398034197627567
builtin 0.08368349098600447

In case 'ccc' in tbl,

ask for forgiveness 0.06165581298409961
conditional 0.0805222729977686
builtin 0.08249014301691204

I’m rather surprised that the conditional is faster than dict.get
but it’s micro-optimization anyway and I think OP was asking for
a faster/shorter way to express it, not performance-wise.

1 Like

I guest we can took this code, and run a loop with predefined randomized dict, and randomized lookup keys so it less of sub-optimal.
Thank for the effort.