Reputation: 73
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];
Upvotes: 3
Views: 180
Reputation: 49802
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.
Upvotes: 4