I am writing a helper function were I need to know what key is missing when a KeyError is raised.
Consider this:
def foo(x:dict):
try:
y = x['A']
except KeyError as ke:
return ke
foo(dict())
As intended, the code above raises a KeyError. More specifically, the repr is KeyError('A').
I want to access that "A" that is missing, but it does not seem to be an attribute of the KeyError object.
Any ideas?
Ps. The reason I’m doing this is because I want to write a function of the form
def check_calculation_dependency_on_data(calculation:callable, data:pd.DataFrame)->list[str]:
'''Returns the mandatory columns data needs to contain for the calculation to work'''
I have a version of the above where data starts with all columns and progressively removes them one at a time (inside a try-except block) to list the columns that raise a KeyError if missing. However, the code would be much more efficient if it starts with an empty dataframe and I add the missing columns one by one until no KeyError is raised.
>Solution :
Alredy answered here Link
map1 = {}
try:
x = map1['key2']
except KeyError as e:
print(e.args[0])