Python keyerror print key

Python KeyError: A Beginner’s Guide

A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.

How to Handle a Python KeyError

Have you just been greeted by a KeyError? Don’t worry! When a KeyError is raised, it means that you are trying to access a key inside a dictionary that does not exist. Handing and fixing this error is easy when you know how.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

KeyErrors can be handled using a try…except block, using the “in” keyword, or by checking for a key in advance using indexing.

In this guide, we’re going to talk about what Python KeyErrors are and why they are raised. We’ll walk through an example of an error and how to fix it so you’ll know how to address KeyErrors in the future.

What is a Python KeyError?

A Python KeyError occurs when you attempt to access an item in a dictionary that does not exist using the indexing syntax. This error is raised because Python cannot return a value for an item that does not exist in a dictionary.

A Python dictionary is a set of key-value pairs that are stored within curly braces (<>):

The keys are “name”, “price”, and “RAM”. Keys appear before a colon in a dictionary.

Let’s see what happens if we try to retrieve the number of USB ports in our dictionary:

print(raspberry_pi["usb_ports"])

This error tells us the key we have specified does not exist. In this case, the missing key is “usb_ports”.

KeyError Python: Solutions

To handle a Python dictionary KeyError you can:

  • Check for a key in advance using indexing
  • Use the “in” keyword to check for a key
  • Use a try…except block.

The solution to handle the KeyError that works best for you will vary depending on your use case.

Use the Dictionary get() Method

The Python dictionary get() method returns a value in a dictionary. You can specify a default value with the get() method. This default value is returned if the name of the key you have specified does not have a value.

Consider the following code:

raspberry_pi = < "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" >get_key = input("What information would you like to retrieve (name, price, RAM)? ") print("The <> for this computer is <>.".format(get_key, raspberry_pi.get(get_key, "not available"))

Let’s run our code using the Python interpreter and see what happens:

What information would you like to retrieve? ALU The ALU for this computer is not available.

Our code uses the dictionary get() method to retrieve “ALU” from our dictionary. No value corresponds with this key name. The get() method returns the default value we have specified, which is “not available”.

Читайте также:  Cpp узнать размер файла

Check for a Key in Advance Using Indexing

You can check for the existence of a key using indexing to avoid encountering a KeyError. If a key is in a dictionary, you can use that key. Otherwise, you can instruct your program to do something else that does not depend on that key.

Let’s write a program that accesses keys in our “raspberry_pi” dictionary in Python. Let’s check if our key is in our dictionary using indexing:

raspberry_pi = < "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" >get_key = input("What information would you like to retrieve (name, price, RAM)? ") if raspberry_pi[get_key]: print("The <> for this computer is <>.".format(get_key, raspberry_pi[get_key])) else: print("This information is not available.")

We have used a Python “if” statement to check if our key exists. “raspberry_pi[get_key]” will only return a value if the key exists. This means that if our key exists, our “if” statement will execute. If our key does not exist, the “else” statement will execute.

Let’s try to find out the RAM for our Raspberry Pi:

What information would you like to retrieve (name, price, RAM)? RAM The RAM for this computer is 4GB.

Now, let’s try to find out about how many USB ports the computer has:

What information would you like to retrieve (name, price, RAM)? USB This information is not available.

Our code does not raise a KeyError! This is because we’ve checked if our key exists first before using it. If we had used raspberry_pi[get_key] inside our “else” statement, our code would return a KeyError.

Using a try…except Block

A Python try…except block will try to run a line of code. If that line of code cannot be run, our code will raise a custom error according to the exceptions you have stated.

We can use a try…except block to determine the existence of an error and stop an unexpected KeyError from helping our Python program.

Let’s define a custom error for our computer example from earlier using a try…except block:

raspberry_pi = < "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" >get_key = input("What information would you like to retrieve (name, price, RAM)? ") try: print("The <> for this computer is <>.".format(get_key, raspberry_pi[get_key])) except KeyError: print("This information is not available.")

We use a try…except block to try to print out a particular piece of information about the Raspberry Pi computer to the console. If our code raises a KeyError anywhere in the “try” block, our code executes the contents of the “except” block.

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Читайте также:  Birthday Reminders for August

Venus, Software Engineer at Rockbot

This means that every time a KeyError is raised, “This information is not available” is printed to the console. Let’s try to find out about the computer’s name:

What information would you like to retrieve (name, price, RAM)? name The name for this computer is Raspberry Pi 4.

Now, let’s try to learn about the computer’s USB port availability:

What information would you like to retrieve (name, price, RAM)? USB This information is not available.

Our code raises a KeyError inside our “try” block. This causes our code to execute the “except” block of code.

Check for a Key in Advance Using in

The “in” keyword is one of Python’s membership operators. It checks if an item is in a list of values. You can use the “in” keyword to check if a key is inside a dictionary.

This program will check if a key exists before printing out its value to the console:

raspberry_pi = < "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" >get_key = input("What information would you like to retrieve (name, price, RAM)? ") if get_key in raspberry_pi: print("The <> for this computer is <>.".format(get_key, raspberry_pi[get_key])) else: print("This information is not available.")

This code will check if the value of “get_key” is a key inside the “raspberry_pi” dictionary. If the key exists, the “if” statement will run. Otherwise, the “else” statement will run. Let’s try to check for information about the computer’s CPU:

What information would you like to retrieve (name, price, RAM)? CPU This information is not available.

Let’s check for the name of the computer:

What information would you like to retrieve (name, price, RAM)? name The name for this computer is Raspberry Pi 4.

Our code works! When we search for a key that does not exist, the “else” statement runs. This means that no KeyError can be raised in our code because we do not attempt to access a key in the “else” block.

Our code works! When we search for a key that does not exist, the “else” statement runs. This means that no KeyError can be raised in our code because we do not attempt to access a key in the “else” block.

Conclusion

A KeyError is raised when you try to access a value from a dictionary that does not exist. To solve a key error, you can check for a key upfront before using it and only use it if the key exists. You can use a try…except block to handle a key error.

For advice on how to learn the Python programming language, check out our comprehensive How to Learn Python guide. You’ll find links to top learning resources, books, and courses in this guide.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

Python: устранение ошибки — KeyError: ‘key_name’

Согласно официальной документации Python 3, ошибка KeyError возникает, когда ключ набора (словаря) не найден в наборе существующих ключей.

Читайте также:  Python print list row

Эта ошибка встречается, когда мы пытаемся получить или удалить значение ключа из словаря, и этот ключ не существует в словаре.

rana@Brahma: ~$ python3 Python 3.5.2 (default, Jul 10 2019, 11:58:48) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = dict() >>> a["key1"] = "value1" >>> print(a["key2"]) Traceback (most recent call last): File "", line 1, in KeyError: 'key2' >>> 

Доступ к ключам словаря:

Для доступа к ключам словаря мы используем квадратные скобки [ ] .

>>> gender = dict() >>> gender["m"] = "Male" >>> gender["f"] = "Female" >>> gender["m"] 'Male' >>> 

Однако вышеуказанный способ, то есть использование квадратных скобок, имеет один недостаток. Если ключ не существует, мы получаем KeyError.

>>> gender["k"] Traceback (most recent call last): File "", line 1, in KeyError: 'k' >>> 

Удаление несуществующего ключа:

>>> del gender["h"] Traceback (most recent call last): File "", line 1, in KeyError: 'h' >>> 

Чтобы справиться с такими случаями, мы можем использовать один из следующих методов, основанных на сценарии.

— Используйте метод get()

Мы можем получить значение ключа из словаря, используя метод get . Если пара ключ-значение не существует для данного ключа в словаре, то возвращается None , иначе возвращается значение, соответствующее этому ключу. Это рекомендуемый способ.

>>> gender.get("m") 'Male' >>> gender.get("k") >>> >>> print(gender.get("k") is None) True >>> 

Вы можете передать второй необязательный параметр в вызове get() , который является значением, возвращаемым, если ключ не существует в словаре. Значением по умолчанию этого второго параметра является None .

— проверить наличие ключа

Мы можем проверить, существует ли какой-либо конкретный ключ в словаре или нет, и затем на основании этого можно предпринять действия. Например:

gender = dict() gender["m"] = "Male" gender["f"] = "Female" if "k" in gender: print("Key k exists in gender") else: print("Key k doesn't exists in gender") 

— Используйте try-exc

Если вы не используете или не хотите использовать метод get для доступа к ключам в словаре, используйте блок try-exc.

gender = dict() gender["m"] = "Male" gender["f"] = "Female" try: value = gender["k"] except KeyError: print("Key error. Do something else") except Exception: print("Some other error") 

— Получить все ключи и перебрать словарь

Мы можем использовать метод keys() , чтобы получить список всех ключей в словаре, а затем выполнить итерацию по этому списку и получить доступ к значениям в словаре.

gender = dict() gender["m"] = "Male" gender["f"] = "Female" keys = gender.keys() for key in keys: print(genderPython keyerror print key) 

— Или вы можете напрямую перебирать словарь для пар ключ и значение, используя метод items().

gender = dict() gender["m"] = "Male" gender["f"] = "Female" for item in gender.items(): print(item[0], item[1]) 

Аналогично, для удаления значения ключа из словаря мы можем использовать метод pop() вместо del.

Однако, в отличие от метода get() , метод pop() выбрасывает keyError , если удаляемый ключ не существует и второй параметр не передается.

Таким образом, чтобы избежать ошибки KeyError в случае удаления ключа, мы должны передать значение по умолчанию, которое будет возвращено, если ключ не найден, в качестве второго параметра для pop()

>>> >>> gender.pop("m") 'Male' >>> gender.keys() dict_keys(['f']) >>> gender.pop("k") Traceback (most recent call last): File "", line 1, in KeyError: 'k' >>> gender.pop("k", None) >>> 

Источник

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