In fact, you have not proven that dictionary searches are faster than two if tests. You have shown that searching in this particular dictionary is faster than these two tests.
Usually, searching a dictionary requires several steps: generate a hash from the key to find a potential match, and then check the potential match by comparing the keys. Sometimes it may take several comparisons if there is a collision with a hash table. If you have user-defined classes for keys, then both of these steps can be slow, they are usually fast for strings, but in one particular case they are really very fast, and you are in this case.
Your dictionary uses keys, which are short strings that correspond to the format of identifiers known at compile time. Python will "put" your strings "R" and "F". Since the strings you use in your tests are also known at compile time, they will be exactly the same instances. What all this means for dictionary searches is that a specialized version of the search is used for a dictionary that has only string keys, the hash has always been pre-computed, and the key comparison is done by comparing the addresses (at least when it succeeds and with your two keys it never fails).
Your real code will be, I assume that I am reading the lines from the input, so it will not have an interned copy of "R". This means that he will need to calculate the hash for each line of input. The addresses do not match, so for each test you need to call the string comparison function. You still have optimizations for having only string keys, and at least it doesn't need to compare common goals for objects that might not be strings.
if do not know anything about object types, so each time they perform a general comparison.
source share