Примеры обработки исключений KeyError в Python
KeyError в Python возникает, когда мы пытаемся получить доступ к ключу из dict, которого не существует. Это один из встроенных классов исключений, вызываемый многими модулями, которые работают с dict или объектами, имеющими пары ключ-значение.
KeyError со словарем
Давайте посмотрим на простой пример, в котором KeyError вызывается программой.
Обработка
Мы можем обработать исключение KeyError с помощью блока try-except. Давайте обработаем вышеуказанное исключение KeyError.
Как избежать ошибки KeyError при доступе к ключу словаря?
Мы можем избежать KeyError, используя функцию get() для доступа к значению ключа. Если ключ отсутствует, возвращается None. Мы также можем указать значение по умолчанию, которое будет возвращаться, если ключ отсутствует.
Выход: Сотрудник [ID: 1, Роль: Нет, Зарплата: 0].
Ошибка ключа, вызванная модулем Pandas
В Pandas DataFrame есть несколько функций, которые вызывают исключение KeyError.
How to Fix KeyError Exceptions in Python

The Python KeyError is an exception that occurs when an attempt is made to access an item in a dictionary that does not exist. The key used to access the item is not found in the dictionary, which leads to the KeyError .
What Causes KeyError
The Python KeyError is raised when a mapping key is not found in the set of existing keys of the mapping. In Python, the most common mapping is the dictionary. When an item in a dictionary is accessed using a key, and the key is not found within the set of keys of the dictionary, the KeyError is raised.
Python KeyError Example
Here’s an example of a Python KeyError raised when trying to access a dictionary item that does not exist:
In the above example, the dictionary employees contains some key-value pairs. An attempt is then made to access an item from employees using the key 4 . Since 4 does not exist in the set of keys of the dictionary, a KeyError is raised:
How to Fix KeyError in Python
To avoid the KeyError in Python, keys in a dictionary should be checked before using them to retrieve items. This will help ensure that the key exists in the dictionary and is only used if it does, thereby avoiding the KeyError . This can be done using the in keyword.
Another solution is to use the .get() function to either retrieve the item using the specified key, or None if it doesn’t exist.
Using the above approach, a check for the key can be added to the earlier example:
Here, a check is performed to ensure that the key 4 exists in the employees dictionary before it is used to retrieve a value. If it does not exist, a message is displayed and the error is avoided:
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
Python Key Error: How Can You Fix it Fast?
The Key Error exception in Python is an exception that most programmers encounter especially when they are getting started with Python dictionaries.
In this article you will learn:
- What does key error mean in Python
- How to fix key errors in Python
- How to handle key errors
What does key error mean?
A Key Error is a way for Python to tell you that you are trying to access a key that doesn’t exist in a dictionary.
Here’s an example, I create a file called keyerror.py…
I define a dictionary that contains countries and their capitals.
First I print the capital of Italy….
…then I print the capital of France.
And here’s what I get when I run it:
As you can see the value related to the first key of the dictionary (Italy) is printed as we want.
But something happens with the second print statement.
A KeyError appears in the output, and that’s because…
Python raises a KeyError when you attempt to access a key that doesn’t exist in a dictionary.
In this case the key ‘France’ doesn’t exist in the countries dictionary.
Notice also how Python can tell at which line of the code the exception has occurred. This is very useful to find the cause of the error quickly when you have hundreds or thousands of lines of code.
How do I fix key errors in Python?
There are two very basic fixes for the key error if your program is simple:
- Avoid referencing the key that doesn’t exist in the dictionary: this can make sense if, for example, the value of the key has been misspelled. It doesn’t apply to this specific case.
- Add the missing key to the dictionary: in this case we would add ‘France’ as a key to the dictionary as part of its initial definition.
But those are not robust approaches and don’t prevent a similar error from occurring again in the future.
Let’s look instead at other two options…
First option
Tell Python not to return a KeyError if we try to access a key that doesn’t exist in the dictionary, but to return a default value instead.
Let’s say we want to return the default value ‘Unknown’ for any keys not present in the dictionary…
Here is how we can do it using the dictionary get() method:
And the output becomes:
So, at least in this way we have more control over the way our program runs.
Second option
Verify if a key exists in a dictionary using the in operator that returns a boolean (True or False) based on the existence of that key in the dictionary.
In the example below I use the in operator together with an if else Python statement to verify if a key exists before accessing its value:
When I run it I see…
This is also a good option!
How do you handle key errors?
In the previous section I have introduced the dictionary get() method as a way to return a default value if a key doesn’t exist in our dictionary.
But, what happens if we don’t pass the default value as second argument to the get() method?
Let’s give it a try, being familiar with built-in methods makes a big difference when you write your code:
Do you know what the output is?
Interestingly this time Python doesn’t raise a KeyError exception…
…the get() method simply returns None if the key doesn’t exist in the dictionary.
This means that we can implement conditional logic in our code based on the value returned by the get() method. Here’s an example:
A nice way to avoid that ugly exception
Avoiding the KeyError with a For Loop
Often a way to handle errors is by using programming constructs that prevent those errors from occurring.
I have mentioned before that a KeyError occurs when you try to access a key that doesn’t exist in a dictionary.
So, one way to prevent a KeyError is by making sure you only access keys that exist in the dictionary.
You could use a for loop that goes through all the keys of the dictionary…
This would ensure that only keys that are present in the dictionary are used in our code.
Let’s have a look at one example:
And the output is…
A for loop can be used to go through all the keys in a dictionary and to make sure you don’t access keys that are not part of the dictionary. This prevents the Python KeyError exception from occurring.
The Generic Approach For Exceptions
Finally, a generic approach you can use with any exceptions is the try except block.
This would prevent Python for raising the KeyError exception and it would allow you to handle the exception in the except block.
This is how you can do it in our example:
As you can see, in this case, the except block is written specifically to handle the KeyError exception.
In this case we could have also used a generic exception (removing KeyError)…
So, do we really need to specify the exception type?
It can be very handy if the try code block could raise multiple types of exceptions and we want to handle each type differently.
Conclusion
Now you have a pretty good idea on how to handle the KeyError exception in Python.
Few options are available to you, choose the one you prefer…
Are you gonna use the get() method or the in operator?
Do you prefer the try except approach?
Let me know in the comments below

Are you getting started with Python?
I have created a checklist for you to quickly learn the basics of Python. You can download it here for free.

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
KeyError in Python – How to Fix Dictionary Error

Ihechikara Vincent Abba

When working with dictionaries in Python, a KeyError gets raised when you try to access an item that doesn’t exist in a Python dictionary.
Here’s a Python dictionary called student :
In the dictionary above, you can access the name «John» by referencing its key – name . Here’s how:
But when you try to access a key that doesn’t exist, you get a KeyError raised. That is:
This is simple to fix when you’re the one writing/testing the code – you can either check for spelling errors or use a key you know exists in the dictionary.
But in programs where you require user input to retrieve a particular item from a dictionary, the user may not know all the items that exist in the dictionary.
In this article, you’ll see how to fix the KeyError in Python dictionaries.
We’ll talk about methods you can use to check if an item exists in a dictionary before executing a program, and what to do when the item cannot be found.
How to Fix the Dictionary KeyError in Python
The two methods we’ll talk about for fixing the KeyError exception in Python are:
- The in keyword.
- The try except block.
Let’s get started.
How to Fix the KeyError in Python Using the in Keyword
We can use the in keyword to check if an item exists in a dictionary.
Using an if. else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.
Here’s an example:
Let’s try to understand the code above by breaking it down.
We first created a dictionary called student which had three items/keys – name , course , and age :
Next, we created an input() function called getStudentInfo : getStudentInfo = input(«What info about the student do you want? «) . We’ll use the value from the input() function as a key to get items from the dictionary.
We then created an if. else statement to check if the value from the input() function matches any key in the dictionary:
From the if. else statement above, if the value from the input() function exists as an item in the dictionary, print(f»The value for your request is
If the value from the input() function doesn’t exist, then print(f»There is no parameter with the ‘
Go on and run the code – input both correct and incorrect keys. This will help validate the explanations above.
How to Fix the KeyError in Python Using a try except Keyword
In a try except block, the try block checks for errors while the except block handles any error found.
Let’s see an example.
Just like we did in the last section, we created the dictionary and an input() function.
We also created different messages for whatever result we get from the input() function.
If there are no errors, only the code in the try block will be executed – this will return the value of the key from the user’s input.
If an error is found, the program will fall back to the except block which tells the user the key doesn’t exist while suggesting possible keys to use.
Summary
In this article, we talked about the KeyError in Python. This error is raised when we try to access an item that doesn’t exist in a dictionary in Python.
We saw two methods we can use to fix the problem.
We first saw how we can use the in keyword to check if an item exists before executing the code.
Lastly, we used the try except block to create two code blocks – the try block runs successfully if the item exists while the except runs if the item doesn’t exist.