'Check keys in dictionary before multiple operations

I have a function that calculates things on a dictionary. Depending on the input to the function, certain entries (arrays) might not be there (if they weren't requested by user).

This is the original snippet, which doesn't check for presence of anything because it's assumed that all these variables will be in dictionary feat (default use case).

delta = feat['sdelta'] + feat['fdelta']
feat['dt'] = delta / feat['theta']
feat['ds'] = delta / feat['sigma']
feat['db'] = delta / feat['beta']
feat['at'] = feat['alpha'] / feat['theta']

I am looking for a strategy to solve it that doesn't involve wrapping every line in a condition that looks like this (related to this question)

if all(elem in feat for elem in ('alpha', 'theta')):
    feat["at"] = feat["alpha"] / feat["theta"]

It might not be possible and I might need to wrap every line in these types of conditionals. I understand this might not be good practice, but what would be the closest to good practice here ?

Update

If the keys are not there, no computation should be made. Basically, skip the new feature if there is no feature to construct it with.



Solution 1:[1]

If you simply want to skip the calculation if one of the keys is missing, the easiest way is to wrap the entire code in a try/except block:

try:
    delta = feat['sdelta'] + feat['fdelta']
    feat['dt'] = delta / feat['theta']
    feat['ds'] = delta / feat['sigma']
    feat['db'] = delta / feat['beta']
    feat['at'] = feat['alpha'] / feat['theta']
except KeyError:
    print('Could not calculate feature due to missing keys')

Note that this still allows other Exceptions to occur and stop the program (for example, a ZeroDivisionError if feat['theta'] happens to be zero). KeyError is only raised when you try to access a value in a dictionary using a key that does not exist.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfaccioni