A KeyError
occurs if you try access a dictionary with a key that does not exist:
fruit = {"name": "apple", "color": "red"}
print(fruit["price"])
The KeyError
exception occurs when you use a key on a dictionary, and the key does not exist.
You can handle the KeyError
in a try...except
statement, see the example below.
Handling the IndexError
in a try...except
statement:
fruit = {"name": "apple", "color": "red"}
try:
print(fruit["price"])
except KeyError:
print("You are trying to access a dictionary item that does not exist!")
except:
print("Something else went wrong")
Track your progress - it's free!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4