Tutorial

Python KeyError Exception Handling Examples

Published on August 4, 2022
author

Pankaj

Python KeyError Exception Handling Examples

1. 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.

2. 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'

3. 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'

4. 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]

5. KeyError Raised by Pandas Module

There are a few functions in Pandas DataFrame that raises KeyError exception.

6. References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.