Does the key check in the dictionary and does it get the value in the same "if" safe?

I think this is safe:

if key in test_dict: if test_dict[key] == 'spam': print('Spam detected!') 

but is it safe?

 if key in test_dict and test_dict[key] == 'spam': print('Spam detected!') 

It should do the same, because checking conditions in python is lazy. It will not try to get the value (and throw an exception, because there is no such key in this type), because the first condition is no longer fulfilled. But can I rely on laziness and use the second example in my programs?

+5
source share
2 answers

Yes, it is safe, Python will be short if the first expression results in False, that is, it will not evaluate the second expression in the if condition.

But the best way to fulfill your condition would be to use .get() , which returns None if the key is not in the dictionary. Example -

 if test_dict.get(key) == 'spam': print('Spam detected!') 
+13
source

and test_dict[key] == 'spam': will only be evaluated if if key in test_dict is True , it will behave exactly like your first code in which you have an attached file.

When you use and , both sides of the expression must be true, so if key in test_dict returns False, then the code will have a short circuit.

Using your and approach is actually most efficient, especially if the left side of the expression is False:

 In [13]: d = {k:k for k in range(10000)} In [14]: timeit 99999 in d and d[100] == "foo" 10000000 loops, best of 3: 48.2 ns per loop In [15]: timeit d.get(9000) == "foo" 10000000 loops, best of 3: 155 ns per loop In [16]: timeit 100 in d and d[100] == "foo 10000000 loops, best of 3: 119 ns per loo In [17]: timeit d.get(100) == "foo" 10000000 loops, best of 3: 141 ns per loop 
+3
source

All Articles