A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3schools.com/python/ref_exception_keyerror.asp below:

Website Navigation


Python KeyError Exception

Python KeyError Exception

❮ Python Exceptions

Example

A KeyError occurs if you try access a dictionary with a key that does not exist:

fruit = {"name": "apple", "color": "red"}
print(fruit["price"])

Try it Yourself » Definition and Usage

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.

Exception Handling Example

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")

Try it Yourself »

❮ Python Exceptions

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