Python keyerror in dict

Ошибка 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:

Читайте также:  Header php файл сохранить

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 – лучший вариант для регулирования потока нашего кода.

Исключения не должны пугать. Мы можем использовать эти методы, чтобы наши программы выполнялись более предсказуемо, если мы понимаем информацию, представленную нам в их обратных трассировках, и первопричину ошибки.

Источник

KeyError in Python – How to Fix Dictionary Error

Ihechikara Vincent Abba

Ihechikara Vincent Abba

KeyError in Python – How to Fix Dictionary Error

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:

student = < "name": "John", "course": "Python", >print(student["age"]) # . KeyError: 'age'

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:

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.

student = < "name": "John", "course": "Python", "age": 20 >getStudentInfo = input("What info about the student do you want? ") if getStudentInfo in student: print(f"The value for your request is ") else: print(f"There is no parameter with the '' key. Try inputing name, course, or age.")

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:

if getStudentInfo in student: print(f"The value for your request is ") else: print(f"There is no parameter with the '' key. Try inputing name, course, or age.")

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 «) will run. student[getStudentInfo] denotes the student dictionary with the value gotten from the input() function acting as a key.

If the value from the input() function doesn’t exist, then print(f»There is no parameter with the » key. Try inputing name, course, or age.») will run telling the user that their input is wrong, with suggestions of the possible keys they can use.

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.

student = < "name": "John", "course": "Python", "age": 20 >getStudentInfo = input("What info about the student do you want? ") try: print(f"The value for your request is ") except KeyError: print(f"There is no parameter with the '' key. Try inputing name, course, or age.")

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.

Источник

Оцените статью