In general terms (not necessarily Python), I tend to prefer the "try-then-tell-me-if-it-went-wrong" method (exceptions) in all but the simplest cases. This is because, in threaded environments or during database access, the underlying data can change between the key check and the value extraction.
If you're not changing the associative array outside of the current thread, then you can do the "check-first-then-extract" method.
But that's for the general case. Here, specifically, you can use the get
method which allows you to specify a default if the key doesn't exist:
return d.get (c, "N/A")
I'll clarify what I stated in the first paragraph. In situations where the underlying data can change between checking and using, you should always use an exception-type operation (unless you have an operation that will not cause a problem, such as d.get()
, mentioned above). Consider for example the following two thread time-lines:
+------------------------------+--------------------+
| Thread1 | Thread2 |
+------------------------------+--------------------+
| Check is NY exists as a key. | |
| | Delete NY key/val. |
| Extract value for NY. | |
+------------------------------+--------------------+
When thread 1 attempts to extract the value, it will get an exception anyway, so you may as well just code for the possibility and remove the initial check.
The comment about databases is also relevant since that's another situation where the underlying data can change. That's why I tend to prefer atomic SQL (where possible) rather than something like getting a list of keys then processing them with individual statements.