- Примеры обработки исключений KeyError в Python
- KeyError со словарем
- Обработка
- Как избежать ошибки KeyError при доступе к ключу словаря?
- Ошибка ключа, вызванная модулем Pandas
- Ошибка KeyError в Python – примеры обработки исключений
- Словарь в Python
- Keyerror в Python
- Механизм обработки ключевой ошибки в Python
- Обычное решение: метод .get()
- Общее решение для keyerror: метод try-except
- Заключение
- Python Dictionary KeyError: None
- Python Dictionary KeyError None
- Handling KeyError: None in a Python dictionary
- Method-1: Using the Python get() method
- Method-2: Using Python try-except blocks
- Method-3: Checking if the key exists using the Python if-else conditional statement with the in operator
- Conclusion:
Примеры обработки исключений KeyError в Python
KeyError в Python возникает, когда мы пытаемся получить доступ к ключу из dict, которого не существует. Это один из встроенных классов исключений, вызываемый многими модулями, которые работают с dict или объектами, имеющими пары ключ-значение.
KeyError со словарем
Давайте посмотрим на простой пример, в котором KeyError вызывается программой.
emp_dict = emp_id = emp_dict['ID'] print(emp_id) emp_role = emp_dict['Role'] print(emp_role)
1 Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/keyerror_examples.py", line 6, in emp_role = emp_dict['Role'] KeyError: 'Role'
Обработка
Мы можем обработать исключение KeyError с помощью блока try-except. Давайте обработаем вышеуказанное исключение KeyError.
emp_dict = 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)
1 Key Not Found in Employee Dictionary: 'Role'
Как избежать ошибки KeyError при доступе к ключу словаря?
Мы можем избежать KeyError, используя функцию get() для доступа к значению ключа. Если ключ отсутствует, возвращается None. Мы также можем указать значение по умолчанию, которое будет возвращаться, если ключ отсутствует.
emp_dict = emp_id = emp_dict.get('ID') emp_role = emp_dict.get('Role') emp_salary = emp_dict.get('Salary', 0) print(f'Employee[ID:, Role:, Salary:]')
Выход: Сотрудник [ID: 1, Роль: Нет, Зарплата: 0].
Ошибка ключа, вызванная модулем Pandas
В Pandas DataFrame есть несколько функций, которые вызывают исключение KeyError.
Ошибка KeyError в Python – примеры обработки исключений
Отображение – это структура данных в Python, которая отображает один набор в другом наборе значений. Словарь Python является наиболее широко используемым для отображения. Каждому значению назначается ключ, который можно использовать для просмотра значения. Ошибка ключа возникает, когда ключ не существует в сопоставлении, которое используется для поиска значения.
В этой статье мы собираемся обсудить ошибки keyerror в Python и их обработку с примерами. Но прежде чем обсуждать ошибку ключа Python, мы узнаем о словаре.
Словарь в Python
Словарь (dict) в Python – это дискретный набор значений, содержащий сохраненные значения данных, эквивалентные карте. Он отличается от других типов данных тем, что имеет только один элемент, который является единственным значением. Он содержит пару ключей и значений. Это более эффективно из-за ключевого значения.
Двоеточие обозначает разделение пары ключа и значения, а запятая обозначает разделение каждого ключа. Этот словарь Python работает так же, как и обычный словарь. Ключи должны быть уникальными и состоять из неизменяемых типов данных, включая строки, целые числа и кортежи.
Давайте рассмотрим пример, чтобы понять, как мы можем использовать словарь (dict) в Python:
# A null Dictionary Dict = <> print("Null dict: ") print(Dict) # A Dictionary using Integers Dict = print("nDictionary with the use of Integers: ") print(Dict) # A Dictionary using Mixed keys Dict = print("nDictionary with the use of Mixed Keys: ") print(Dict) # A Dictionary using the dict() method Dict = dict() print("nDictionary with the use of dict(): ") print(Dict) # A Dictionary having each item as a Pair Dict = dict([(1, 'Hello'),(2, 'World')]) print("nDictionary with each item as a pair: ") print(Dict)
Null dict: <> nDictionary with the use of Integers: nDictionary with the use of Mixed Keys: nDictionary with the use of dict(): nDictionary with each item as a pair:
Keyerror в Python
Когда мы пытаемся получить доступ к ключу из несуществующего dict, Python вызывает ошибку Keyerror. Это встроенный класс исключений, созданный несколькими модулями, которые взаимодействуют с dicts или объектами, содержащими пары ключ-значение.
Теперь мы знаем, что такое словарь Python и как он работает. Давайте посмотрим, что определяет Keyerror. Python вызывает Keyerror всякий раз, когда мы хотим получить доступ к ключу, которого нет в словаре Python.
Логика сопоставления – это структура данных, которая связывает один фрагмент данных с другими важными данными. В результате, когда к сопоставлению обращаются, но не находят, возникает ошибка. Это похоже на ошибку поиска, где семантическая ошибка заключается в том, что искомого ключа нет в его памяти.
Давайте рассмотрим пример, чтобы понять, как мы можем увидеть Keyerror в Python. Берем ключи A, B, C и D, у которых D нет в словаре Python. Хотя оставшиеся ключи, присутствующие в словаре, показывают вывод правильно, а D показывает ошибку ключа.
# Check the Keyerror ages= print(ages['A']) print(ages['B']) print(ages['C']) print(ages['D'])
45 51 67 Traceback(most recent call last): File "", line 6, in KeyError: 'D'
Механизм обработки ключевой ошибки в Python
Любой, кто сталкивается с ошибкой Keyerror, может с ней справиться. Он может проверять все возможные входные данные для конкретной программы и правильно управлять любыми рискованными входами. Когда мы получаем KeyError, есть несколько обычных методов борьбы с ним. Кроме того, некоторые методы могут использоваться для обработки механизма ошибки ключа.
Обычное решение: метод .get()
Некоторые из этих вариантов могут быть лучше или не могут быть точным решением, которое мы ищем, в зависимости от нашего варианта использования. Однако наша конечная цель – предотвратить возникновение неожиданных исключений из ключевых ошибок.
Например, если мы получаем ошибку из словаря в нашем собственном коде, мы можем использовать метод .get() для получения либо указанного ключа, либо значения по умолчанию.
Давайте рассмотрим пример, чтобы понять, как мы можем обработать механизм ошибки ключа в Python:
# List of vehicles and their prices. vehicles = vehicle = input("Get price for: ") vehicle1 = vehicles.get(vehicle) if vehicle1: print(" is rupees.") else: print("'s cost is unknown.")
Get price for: Car Car is 300000 rupees.
Общее решение для keyerror: метод try-except
Общий подход заключается в использовании блока try-except для решения таких проблем путем создания соответствующего кода и предоставления решения для резервного копирования.
Давайте рассмотрим пример, чтобы понять, как мы можем применить общее решение для keyerror:
# Creating a dictionary to store items and prices items = try: print(items["Book"]) except: print("The items does not contain a record for this key.")
Здесь мы видим, что мы получаем стоимость книги из предметов. Следовательно, если мы хотим напечатать любую другую пару «ключ-значение», которой нет в элементах, она напечатает этот вывод.
# Creating a dictionary to store items and prices items = try: print(items["Notebook"]) except: print("The items does not contain a record for this key.")
The items does not contain a record for this key.
Заключение
Теперь мы понимаем некоторые распространенные сценарии, в которых может быть выброшено исключение Python Keyerror, а также несколько отличных стратегий для предотвращения их завершения нашей программы.
В следующий раз, когда мы столкнемся с ошибкой Keyerror, мы будем знать, что это, скорее всего, связано с ошибочным поиском ключа словаря. Посмотрев на последние несколько строк трассировки, мы можем получить всю информацию, которая нам понадобится, чтобы выяснить, откуда взялась проблема.
Если проблема заключается в поиске ключа словаря в нашем собственном коде, мы можем использовать более безопасную функцию .get() с возвращаемым значением по умолчанию вместо запроса ключа непосредственно в словаре. Если наш код не вызывает проблемы, блок try-except – лучший вариант для регулирования потока нашего кода.
Исключения не должны пугать. Мы можем использовать эти методы, чтобы наши программы выполнялись более предсказуемо, если мы понимаем информацию, представленную нам в их обратных трассировках, и первопричину ошибки.
Python Dictionary KeyError: None
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 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:
This way we can use the get() method to handle KeyError 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.
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.
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.
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.