Do dictionaries in Python offer the best way to formulate switch-like statements?
I'm hoping there's no performance or other disadvantage in attempting to avo开发者_高级运维id 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];
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.
精彩评论