Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Handling NameError Exception in Python
Next article icon

How to handle KeyError Exception in Python

Last Updated : 30 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to handle KeyError exceptions in Python programming language.

What are Exceptions?

  • It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.
  • Exceptions are runtime errors because, they are not identified at compile time just like syntax errors which occur due to wrong indentation, missing parentheses, and misspellings. 
  • Examples of built-in exceptions in Python – KeyError exception, NameError, ImportError, ZeroDivisionError, FloatingPointError, etc.

What is KeyError Exception?

A KeyError Exception occurs when we try to access a key that is not present. For example, we have stored subjects taken by students in a dictionary with their names as a key and subjects as a value and if we want to get the value of a key that doesn’t exist then we get a KeyError exception. Let’s understand this by an example.

Example:

Python3




# Creating a Dictionary
subjects = {'Sree': 'Maths',
            'Ram': 'Biology',
            'Shyam': 'Science',
            'Abdul': 'Hindi'}
  
# Printing the subject of Fharan
print(subjects['Fharan'])
 
 

Explanation: In the above example we have created a dictionary and tried to print the subject of ‘Fharan’ but we got an error in the output as shown below because that key is not present in our dictionary which is called a Python KeyError exception.

Output:

Traceback (most recent call last):    File "4119e772-3398-41b7-816b-6b20791538e9.py", line 7, in <module>      print(subjects['Fharan'])  KeyError: 'Fharan'

Methods to handle KeyError exception

Method 1: Using Try, Except keywords

The code that can(may) cause an error can be put in the try block and the code that handles it is to be included in the except block so that abrupt termination of the program will not happen because the exception is being handled here by the code in the expected block. To know more about try, except refer to this article Python Try Except.

Example:

Python3




# Creating a Dictionary
subjects = {'Sree': 'Maths',
            'Ram': 'Biology',
            'Shyam': 'Science',
            'Abdul': 'Hindi'}
# try block
try:
    print('subject of Fharan is:',
          subjects['Fharan'])
# except Block
except KeyError:
    print("Fharan's records doesn't exist")
 
 

Explanation: In this example, subjects[‘Fharan’] raises an exception but doesn’t halt the program because the exception is caught by expect block where some action is being done (printing a message that “Fharan’s records doesn’t exist”)

Output:

Fharan's records doesn't exist

Method 2: Using get() method

The get() method will return the value specified by the given key, if a key is present in the dictionary, if not it will return a default value given by the programmer. If no default value is specified by the programmer, it returns “None” as output.

Example:

Python3




# Creating a Dictionary
subjects = {'Sree': 'Maths',
            'Ram': 'Biology',
            'Shyam': 'Science',
            'Abdul': 'Hindi'}
# Storing the subject of student
# that doesn't exist
sub = subjects.get('sreelekha')
# Printing the Subject
print(sub)
 
 

Output: In the above example, there is no key “sreeram” hence, it returns “None”.

None

If a default value is to be returned instead of “None”, we need to specify the default value in this way:  

sub = subjects.get(‘sreeram’, “Student doesn’t exist”)

Example :

Python3




subjects = {'sree': 'Maths', 'ram': 'Biology'}
sub = subjects.get('sreeram', "Student doesn't exist")
print(sub)
 
 

Output:

Student doesn't exist

To know more about exception handling in python please refer to this article Python Exception Handling.



Next Article
Handling NameError Exception in Python

S

sreelekhakolla957
Improve
Article Tags :
  • Python
  • Technical Scripter
  • Technical Scripter 2022
Practice Tags :
  • python

Similar Reads

  • Handling NameError Exception in Python
    Prerequisites: Python Exception Handling There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functio
    2 min read
  • Handling OSError exception in Python
    Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below
    2 min read
  • How to Handle the MemoryError in Python
    One common issue developers may encounter is the dreaded MemoryError. This error occurs when a program runs out of available memory, causing it to crash. In this article, we will explore the causes of MemoryError, discuss common scenarios leading to this error, and present effective strategies to ha
    3 min read
  • Python Exception Handling
    Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
    7 min read
  • Handling TypeError Exception in Python
    TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeErro
    3 min read
  • How to log a Python exception?
    To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an
    2 min read
  • How to handle a Python Exception in a List Comprehension?
    In Python, there are no special built-in methods to handle exceptions in the list comprehensions. However, exceptions can be managed using helper functions, try-except blocks or custom exception handling. Below are examples of how to handle common exceptions during list comprehension operations: Han
    3 min read
  • Multiple Exception Handling in Python
    Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they
    3 min read
  • How to Add Duplicate Keys in Dictionary - Python
    In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will explore several techniques to store multiple values for a single dictionary key. Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique.
    3 min read
  • How to Fix - KeyError in Python – How to Fix Dictionary Error
    Python is a versatile and powerful programming language known for its simplicity and readability. However, like any other language, it comes with its own set of errors and exceptions. One common error that Python developers often encounter is the "KeyError". In this article, we will explore what a K
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences