W3docs

I'm getting Key error in python

A KeyError in Python is raised when a dictionary key is not found in the dictionary.

A KeyError in Python is raised when a dictionary key is not found in the dictionary. Here's an example of a simple code snippet that will raise a KeyError:

Code snippet that will raise a KeyError in Python

my_dict = {"a": 1, "b": 2}
print(my_dict["c"])

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

In this example, the code is trying to access the value associated with the key "c" in the dictionary "my_dict", but "c" is not a key in the dictionary, so a KeyError is raised. To avoid this error, you can use the .get() method or the in keyword to check if the key is present in the dictionary before trying to access it.

Using .get method or the "in" keyword to check if the key is present in the dictionary before trying to access it in Python

my_dict = {"a": 1, "b": 2}

# Using .get() method
value = my_dict.get("c", "Key not found")
print(value)

# Using `in` keyword
if 'c' in my_dict:
    print(my_dict['c'])
else:
    print("Key not found")

In this example, the .get() method is used to safely access the value associated with the key "c" in the dictionary. If the key is not found, the .get() method will return the default value "Key not found" instead of raising an error.