Is there a more Pythonic way to combine an Else: statement and an Except:?
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cases, the <code>"overall_weight"</code> keywords should be replaced with <code>"N/A"</code>. I was wondering if there was a more pythonic way to combine the <code>KeyError</code> exception and the <code>else</code> to both go to <code>nObject.TextString = "N/A"</code> so its not typed twice.</p>

<pre><code>if nObject.TextString == "overall_weight":
    try:
        if self.var.jobDetails["Overall Weight"]:
            nObject.TextString = self.var.jobDetails["Overall Weight"]
        else:
            nObject.TextString = "N/A"
    except KeyError:
        nObject.TextString = "N/A"
</code></pre>

<p>Edit: For clarification for future visitors, there are only 3 cases I need to take care of and the correct answer takes care of all 3 cases without any extra padding.</p>

<ol>
<li><p><code>dict[key]</code> exists and points to a non-empty string. <code>TextString</code> replaced with the value assigned to <code>dict[key]</code>.</p></li>
<li><p><code>dict[key]</code> exists and points to a empty string. <code>TextString</code> replaced with <code>"N/A"</code>.</p></li>
<li><p><code>dict[key]</code> doesn't exist. <code>TextString</code> replaced with <code>"N/A"</code>.</p></li>
</ol>

<p>I think this is a good case for setting the default value in advance</p>

<pre><code>if nObject.TextString == "overall_weight":
    nObject.TextString = "N/A"
    try:
        if self.var.jobDetails["Overall Weight"]:
            nObject.TextString = self.var.jobDetails["Overall Weight"]
    except KeyError:
        pass
</code></pre>

<p><strong>RADICAL RETHINK</strong></p>

<p>Ditch that first answer (just keeping it because it got an upvote). If you really want to go pythonic, (and you always want to set a value on TextString) replace the whole thing with</p>

<pre><code>nObject.TextString = (nObject.TextString == "overall_weight"
    and self.var.jobDetails.get("Overall Weight")
    or "N/A")
</code></pre>

<p>Python <code>and</code> and <code>or</code> operations return their last calculated value, not True/False and you can use that to walk through the combinations.</p>

python python-2.7