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>If you want to avoid the repetitiveness of typing <code>.get(attr, '_')</code> for each key, you can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>, setting it to return <code>_</code> when a key is trying to be accessed but missing.</p>

<pre><code>from collections import defaultdict

data = {
    'foo': 'foo_value',
}

ret_dict = defaultdict(lambda: '_')
ret_dict.update(data)

print(ret_dict['foo'])  # 'foo_value'
print(ret_dict['bar'])  # '_'
</code></pre>

python