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> function for dictionaries. It will return <code>None</code> if the key doesn't exist or if you specify a second value, it will set that as the default. Then your syntax will look like:</p>

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

python python-2.7