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:
How to Add Duplicate Keys in Dictionary - Python
Next article icon

How to Fix - KeyError in Python – How to Fix Dictionary Error

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 KeyError is, why it occurs, and various methods to fix it.

Understanding KeyError in Python

A 'KeyError' occurs when you try to access a key in a dictionary that doesn't exist. In Python, dictionaries are composed of key-value pairs, and keys are used to access the corresponding values. If you attempt to access a key that is not present in the dictionary, Python raises a 'KeyError' to inform you that the key is missing. Let's look at some examples where a 'KeyError' can be generated and how to fix them.

Accessing Dictionary Element that is not present

Here in this code, we are trying to access the element in the dictionary which is not present.

Example: In this scenario, we have created a dictionary called 'my_dict' with the keys "name", "age", and "city". However, we are attempting to access a key called "gender", which does not exist in the dictionary.

Python3
my_dict = {'name': 'Selena', 'age': 30, 'city': 'New York'} print(my_dict['gender']) 

Output

Error Explanation: When Python encounters the line print(my_dict['gender']), it tries to find the key "gender" in my_dict. Since "gender" is not one of the keys in the dictionary, Python raises a 'KeyError' with the message "gender".

--------------------------------------------------------------------------- KeyError                                  Traceback (most recent call last) <ipython-input-8-e82a6939bd7b> in <module> Cell 1 line 5       2 my_dict = {'name': 'Selena', 'age': 30, 'city': 'New York'}       4 # Accessing a non-existent key ----> 5 print(my_dict['gender'])  # KeyError: 'gender'  KeyError: 'gender'

Solution

To avoid the 'KeyError', it's essential to check if a key exists in the dictionary before attempting to access it. We can use the 'in' keyword or the 'get()' method to handle this situation gracefully.

Python
my_dict = {'name': 'Selena', 'age': 30, 'city': 'New York'} if 'gender' in my_dict:     print(my_dict['gender']) else:     print("Key 'gender' does not exist") gender = my_dict.get('gender', 'Key not found') print(gender) 

Output:

Key 'gender' does not exist Key not found 

KeyError in JSON Data

One common real-world scenario where people often encounter a 'KeyError' with nested dictionaries involves working with JSON data. JSON (JavaScript Object Notation) is a widely used data format for storing and exchanging structured data. When you load JSON data into Python, it is typically represented as a nested dictionary.

Example: Considering a situation where we have a JSON object representing information about products, and we want to access a specific property of a product.

In this example, we are trying to access the "description" key of the first product, which appears to be nested within the "products" list. However, the "description" key does not exist in the JSON data, which results in a 'KeyError'.

Python
product_data = {     "products": [         {             "id": 1,             "name": "Laptop",             "price": 999.99         },         {             "id": 2,             "name": "Smartphone",             "price": 599.99         }     ] } description = product_data["products"][0]["description"] 

Output:

--------------------------------------------------------------------------- KeyError                                  Traceback (most recent call last) <ipython-input-8-e82a6939bd7b> in <module> Cell 1 line 1       2 product_data = {       3     "products": [       4         {    (...)      14     ]      15 }      17 # Attempting to access the description of the first product ---> 18 description = product_data["products"][0]["description"]  KeyError: 'description' 

Error Explanation: This type of 'KeyError' can be challenging to troubleshoot in real-world applications, especially when dealing with large and complex JSON structures, as it may not always be immediately obvious which key is missing.

Solution

To avoid this 'KeyError', you should check the existence of keys at each level of nesting before attempting to access them. Here's how you can modify the code to handle this situation:

Python
product_data = {     "products": [         {             "id": 1,             "name": "Laptop",             "price": 999.99         },         {             "id": 2,             "name": "Smartphone",             "price": 599.99         }     ] } if "products" in product_data and len(product_data["products"]) > 0:     first_product = product_data["products"][0]     if "description" in first_product:         description = first_product["description"]     else:         description = "Description not available" else:     description = "No products found"      print(description) 

Output:

Description not available 

The solution systematically checks for the existence of keys within nested dictionaries. It verifies the presence of the "products" key in product_data and ensures a non-empty list. If found, it accesses the first product's dictionary and checks for the "description" key, preventing 'KeyError' with a default value if absent. It also handles missing or empty "products" keys by providing an alternative message, ensuring robust handling of nested dictionaries in real-world data scenarios like JSON.

Alternative Method

We can also handle 'KeyError' situation by using an approach that uses "try", "except" block. Let's take the above example and here is the alternative code for the same:-

We attempt to access the "description" key within the first product, just like in the previous solution. We use a try...except block to catch any 'KeyError' that may occur when accessing the key. If a 'KeyError' occurs, we set description to "Description not available" . Additionally, we include an except block to catch other potential errors, such as IndexError (in case the "products" list is empty) and TypeError (if product_data is not a properly formatted dictionary). In either of these cases, we set description to "No products found".

Python3
product_data = {     "products": [         {             "id": 1,             "name": "Laptop",             "price": 999.99         },         {             "id": 2,             "name": "Smartphone",             "price": 599.99         }     ] } try:     first_product = product_data["products"][0]     description = first_product["description"] except KeyError:     print("Description not available") except (IndexError, TypeError):     print("No products found") 

Output

Description not available 

Next Article
How to Add Duplicate Keys in Dictionary - Python
author
meghaqweera72
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • How to read Dictionary from File in Python?
    A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.
    2 min read
  • How to handle KeyError Exception in Python
    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, th
    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 Add Function in Python Dictionary
    Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
    5 min read
  • Python | Set 4 (Dictionary, Keywords in Python)
    In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value ca
    5 min read
  • How to implement Dictionary with Python3?
    This program uses python's container called dictionary (in dictionary a key is associated with some information). This program will take a word as input and returns the meaning of that word. Python3 should be installed in your system. If it not installed, install it from this link. Always try to ins
    3 min read
  • How to Add Same Key Value in Dictionary Python
    Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python. Adding
    2 min read
  • Get Key from Value in Dictionary - Python
    The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
    6 min read
  • Python - Find the Common Keys from two Dictionaries
    In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see differ
    4 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    2 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