• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Python KeyError

Python KeyError

Author: Aditya Raj
Last Updated: November 3, 2021

You might have encountered KeyError while working with dictionaries in python. In this article, we will discuss what a KeyError is, how it occurs and how we can avoid a KeyError while working with a python dictionary.

Table of Contents
  1. What is Python KeyError ?
  2. How to avoid Python KeyError exceptions?
    1. Using If else statement
    2. Using the get() method
    3. Using Try Except
  3. Conclusion

What is Python KeyError ?

In simple terms, KeyError is an exception raised by a python program when we try to access a value from a dictionary with a key that is not present in the dictionary. 

For example, look at the following program. Here the dictionary myDict has keys 1, 2, and 3 with values 1, 4, and 9 associated with the keys. When we try to access the dictionary with a key 4, the program raises a KeyError. This is due to the reason that 4 is not present in the dictionary as a key.

myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
print(myDict[4])

Output:

The dictionary is: {1: 1, 2: 4, 3: 9}
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string.py", line 3, in <module>
    print(myDict[4])
KeyError: 4

How to avoid Python KeyError exceptions?

There are various ways to avoid KeyError exceptions. Let us discuss them one by one.

Using If else statement

Using the if else statement, we can check if a given key is present in the keys of the dictionary before accessing the value. It helps us to avoid the KeyError exception.

myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
if key in myDict.keys():
    print(myDict[key])
else:
    print("{} not a key of dictionary".format(key))

Output:

The dictionary is: {1: 1, 2: 4, 3: 9}
4 not a key of dictionary

The drawback here is that  each time we have to check if a given key is present in the keys of the dictionary. This extra work can be avoided if we use the get() method to access values from the dictionary.

Using the get() method

The get() method, when invoked on a dictionary, takes the given key and an optional value as input. If the given key is present in the dictionary, it gives the associated value to the key as output as follows.

myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 3
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key))

Output:

The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 3
Value associated to the key is: 9

When the given key is not present in the dictionary, it returns None if no optional value is passed.

myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key))

Output:


The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Value associated to the key is: None

If we pass an optional value as input to the get() method, it returns the value when the given key is not present in the dictionary.

myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key = 4
print("Key is:",key)
print("Value associated to the key is:",myDict.get(key,16))

Output:

The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Value associated to the key is: 16

Using Try Except

We can use python try except blocks to handle the KeyError exception. For that, we will execute the code to access the value using the given key in the try block and will handle the exception in the except block as follows.

myDict = {1: 1, 2: 4, 3: 9}
print("The dictionary is:", myDict)
key=4
print("Key is:",key)
try:
    val=myDict[key]
    print("Value associated to the key is:",val)
except KeyError:
    print("Key not present in Dictionary")

Output:

The dictionary is: {1: 1, 2: 4, 3: 9}
Key is: 4
Key not present in Dictionary

Conclusion

In this article, we have discussed KeyErrors and the ways to handle them. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary โ€“ How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 ยท PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us