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>Use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>.get</code></a> method of <a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict" rel="nofollow"><code>dict</code></a>:</p>

<pre><code>def get_data(data):
    return {
        # If you want to accept falsy values from API:
        'foo': data.get('foo', '_'),

        # If you want to override falsy values from API:
        'bar': data.get('bar') or '_',
    }
</code></pre>

<p><code>.get</code> returns its second argument (<code>None</code> by default) if a dict doesn't have requested key, so it is always safe to use it in uncertain situations. </p>

<p>Example:</p>

<pre><code>&gt;&gt;&gt; data = {'foo': False, 'bar': False}
&gt;&gt;&gt; get_data(data)
{'bar': '_', 'foo': False}
</code></pre>

python