Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to I get the missing key from a KeyError in Python?

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').

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading