How to programmatically catch which command failed on a try block
<p>I'm trying to get some data from an JSON API. I don't want all the data that the API returns so I wrote a method that reads all the data and returns a dictionary with the relevant fields. Sometimes though, some data are missing and I would like to replace the fields that are missing with an underscore. A sample of the method is like that;  </p>

<pre><code>return {
    'foo': data['foo'],
    'bar': data['bar']
 }
</code></pre>

<p>If a field is missing from the data, this throughs a KeyError. Is it possible to catch programmatically which field produced the error, in a single try-except block and not write a try-except block for every field?</p>

<pre><code>try:
    ret_dict =  {
        'foo': data['foo'],
        'bar': data['bar']
    }
 except KeyError:
    ret_dict[thefailurekey] = '_'
</code></pre>

<p>instead of  </p>

<pre><code>ret_dict = {}
try:
    ret_dict['foo'] = data['foo']
except KeyError:
    ret_dict['foo'] = '_'
try:
    ret_dict['bar'] = data['bar']
except:
    ret_dict['bar'] = '_'
</code></pre>

<p>Thank you</p>

<p>Instead of using try block, you can use <code>dict.get(key, default_val)</code></p>

<p>For example:</p>

<pre><code>ret_dict = dict(
    foo=data.get('foo', '-'),
    bar=data.get('bar', '-')
)

return ret_dict
</code></pre>

python