Python KeyError Exception Handling Examples

What is Python KeyError Exception?

Python KeyError is raised when we try to access a key from dict, which doesn’t exist. It’s one of the built-in exception classes and raised by many modules that work with dict or objects having key-value pairs.

Python KeyError with Dictionary

Let’s look at a simple example where KeyError is raised by the program.

emp_dict = {'Name': 'Pankaj', 'ID': 1}

emp_id = emp_dict['ID']
print(emp_id)

emp_role = emp_dict['Role']
print(emp_role)

Output:

1
Traceback (most recent call last):
  File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/keyerror_examples.py", line 6, in <module>
    emp_role = emp_dict['Role']
KeyError: 'Role'

Python KeyError Exception Handling

We can handle the KeyError exception using the try-except block. Let’s handle the above KeyError exception.

emp_dict = {'Name': 'Pankaj', 'ID': 1}

try:
    emp_id = emp_dict['ID']
    print(emp_id)

    emp_role = emp_dict['Role']
    print(emp_role)
except KeyError as ke:
    print('Key Not Found in Employee Dictionary:', ke)

Output:

1
Key Not Found in Employee Dictionary: 'Role'

Avoiding KeyError when accessing Dictionary Key

We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.

emp_dict = {'Name': 'Pankaj', 'ID': 1}

emp_id = emp_dict.get('ID')
emp_role = emp_dict.get('Role')
emp_salary = emp_dict.get('Salary', 0)

print(f'Employee[ID:{emp_id}, Role:{emp_role}, Salary:{emp_salary}]')

Output:

Employee[ID:1, Role:None, Salary:0]

Source: digitalocean.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

How to Manage User Groups in Linux Step-by-Step

Linux Basics, Tutorial

Linux file permissions with this comprehensive guide. Understand how to utilize chmod and chown commands to assign appropriate access rights, and gain insights into special permission bits like SUID, SGID, and the sticky bit to enhance your system’s security framework.

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

Apache Airflow on Ubuntu 24.04 with Nginx and SSL

Apache, Tutorial

This guide provides step-by-step instructions for installing and configuring the Cohere Toolkit on Ubuntu 24.04. It includes environment preparation, dependency setup, and key commands to run language models and implement Retrieval-Augmented Generation (RAG) workflows. Ideal for developers building AI applications or integrating large language models into their existing projects.