views:

78

answers:

1

I'm hoping there's no performance or other disadvantage in attempting to avoid long chains of conditional if/elif statements this way:

errstr = {404: "404 Not Found",
          405: "405 Method Not Allowed"}
if code in errstr:
       print errstr[code];
+4  A: 

Yes, they're the best solution, because they are implemented as hash tables, giving approximately constant lookup times (if the hash function is good). Binary trees would give logarithmic lookup time, if chains linear time. Hash tables are usually the way to go if one has to represent a mapping from a not-too-large finite set to some other set.

BTW, Python is a very good language for learning, because in Python, often the simplest solution is also the best one.

Philipp
"... often the simplest solution is also the best one." is true in a lot of situations, but yes, especially in Python.
Ryan Kinal
Thank you so much Philipp! I really appreciate your timely answer and insight.
Lost
@Ryan: As an opposite I'd name languages such as Bash: if you want to iterate over array *X*, you have to specify it as `"${X[@]}"`—leaving out the braces or the brackets or the quotes will do something, but not what was intended. Here the correct solution is most complicated.
Philipp
That's a syntax-ism, not a "solution".
Nick Presta