Bootstrap FreeKB - Python (Scripting) - Resolve KeyError
Python (Scripting) - Resolve KeyError

Updated:   |  Python (Scripting) articles

Let's say a Python script is returning KeyError.

Traceback (most recent call last):
  File "/home/c065234/testing.py", line 12, in <module>
    print(dictionary['bogus'])
KeyError: 'bogus'

 

Here is a super simple script that will return KeyError. In this example, KeyError is being returned because dictionary does not contain the "bogus" key.

#!/usr/bin/python

dictionary = {
  "foo": "Hello",
  "bar": "World"
}

print(dictionary['bogus'])

 

try / except / else or try / except / finally can be used to do something when a KeyError exception is raised.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}

try:
  dictionary['bogus']
except KeyError:
  print("dictionary does not contain key 'bogus'")
  pass
else:
  print(dictionary['bogus'])

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b566ae in the box below so that we can be sure you are a human.