In this Python tutorial, we will see how to handle KeyError: None in a Python dictionary using different methods. We will also see different examples.
Python Dictionary KeyError None
A KeyError: None occurs when we try to access a value in a dictionary using a key that is None and not present in the dictionary.
A dictionary in Python is a data structure that stores data as a pair of a key and a value. When we access a value in the dictionary, we use the corresponding key. If we try to access a key that does not exist in the dictionary, Python raises a KeyError.
If we specifically try to access a key that is None, and there is no such key in the dictionary, we will get KeyError: None.
In this Python dictionary, we have the populations of some major US cities. The keys are the names of the cities and the values are the respective populations. If we try to access the population of a city using the None key, we will encounter a KeyError: None because there is no None key in the dictionary. Here’s an example:
city_populations = {
'New York': 8399000,
'Los Angeles': 3971000,
'Chicago': 2726000,
'Houston': 2323000,
'Phoenix': 1748000,
}
print(city_populations[None])
The output is KeyError: None because None is a not valid key in our city_populations dictionary. We only have keys for ‘New York’, ‘Los Angeles’, ‘Chicago’, ‘Houston’, and ‘Phoenix’.
Traceback (most recent call last):
File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 9, in <module>
print(city_populations[None])
~~~~~~~~~~~~~~~~^^^^^^
KeyError: None
Handling KeyError: None in a Python dictionary
There are several ways to handle Python dictionary KeyError: None, Here are some most common and effective ways to do so:
- Using the get() method
- Using try-except blocks
- Checking if the key exists using the if-else conditional statement with the in operator.
Method-1: Using the Python get() method
The get() method in a Python dictionary returns the value for the given key if it exists in the dictionary. If not, it will return None or the default value specified.
Here, we have a dictionary of famous landmarks in the US and the states they are located in:
us_landmarks = {
'Statue of Liberty': 'New York',
'Mount Rushmore': 'South Dakota',
'Golden Gate Bridge': 'California',
'Grand Canyon': 'Arizona',
'White House': 'Washington, D.C.'
}
print(us_landmarks.get('Disneyland'))
The output of this Python code is: If we want to search for a landmark that is not present, the get() method can be used to return a default value, or None if no default is provided:
None
This way we can use the get() method to handle KeyError in the Python dictionary.
Read How to remove a key without an error in the Python dictionary
Method-2: Using Python try-except blocks
We can catch and handle exceptions in Python using try-except blocks. This method is useful when we’re not sure if a key exists in a Python dictionary. The try block contains the block of code which can give errors, and the except block contains the code which will execute if any errors occur.
Here we have, The U.S. states as keys and their capital as values for a Python dictionary, we can use a try-except
block to catch a KeyError
when accessing a key that might not be present:
us_state_capitals = {
'California': 'Sacramento',
'Texas': 'Austin',
'Florida': 'Tallahassee',
'New York': 'Albany',
'Washington': 'Olympia'
}
try:
print(us_state_capitals[None])
except KeyError:
print("State not found")
Output: This will print State not found instead of raising a KeyError.
State not found
This way we can use, the try-except block to handle the KeyError in a Python dictionary.
Method-3: Checking if the key exists using the Python if-else conditional statement with the in operator
In this method, We will use the if statement with in operator to check whether the key exists in the dictionary, if not present, returns it with the else statement to not show KeyError in Python.
Here, we have a dictionary that lists the biggest tech companies in the US and their headquarters:
tech_companies = {
'Apple': 'Cupertino, California',
'Microsoft': 'Redmond, Washington',
'Google': 'Mountain View, California',
'Facebook': 'Menlo Park, California',
'Amazon': 'Seattle, Washington'
}
if None in tech_companies:
print(tech_companies[None])
else:
print("Company not found")
The Output will print Company not found instead of raising a KeyError.
Company not found
This way we can use, the if-else statements with the in operator to handle the KeyError in the Python dictionary.
Conclusion:
While encountering a KeyError: None can interrupt code execution, Python provides several methods to handle this scenario gracefully, allowing the code to continue running even if the key is absent.
The get() method of a dictionary can be used to return a default value when the key is not present. Exception handling with try-except blocks offers another means to catch KeyError. Finally, using the if-else statement with the in keyword to check the existence of a key prior to accessing it helps us avoid the KeyError entirely.
You may like to read:
- Python dictionary key error
- ValueError: math domain error in Python [Causes & Fixes]
- KeyError: 0 in a Python dictionary
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.