Do Python dictionaries really offer a better way to formulate operator expressions?

I hope there is no performance or other drawback in trying to avoid long chains of conditional if / elif statements in this way:

errstr = {404: "404 Not Found",
          405: "405 Method Not Allowed"}
if code in errstr:
       print errstr[code];
+3
source share
1 answer

Yes, this is the best solution because they are implemented as hash tables giving approximately constant search time (if the hash function is good). Binary trees give a logarithmic search time, if- linear time. Hash tables are generally suitable if you need to represent a mapping from a not-so-large finite set to some other set.

BTW, Python - , Python .

+4

Source: https://habr.com/ru/post/1752274/


All Articles