Python (Scripting) - Resolve KeyError

by
Jeremy Canfield |
Updated: November 06 2023
| 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