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>Use <code>.get()</code> with a default argument of <code>"N/A"</code> which will be used if the key does not exist:</p>

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

<h1>Update</h1>

<p>If empty strings need to be handled, simply modify as follows:</p>

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

<p>This will set <code>nObject.TextString</code> to "N/A" if a <code>KeyError</code> is raised, or if the value is retrieved is empty: <code>''</code>, <code>[]</code>, etc.</p>

python python-2.7