Checking the Existence of Dictionary Keys
00:00 At the end of the last lesson, you saw that Python raises an error when you want to access a value of a dictionary with a key that doesn’t exist. In this lesson, you’ll learn how to prevent key errors by checking for keys first.
Instead of working in the IDLE Shell, we are working in the IDLE scripting window now. On the right side, you see the dictionary
my_dog. It contains four items with the keys
"nicknames". I also added the fourth key,
"hungry" with the value
As you learned in the last lesson, you can access an item by writing
my_dog, square brackets (
), and then the key. In this case, let’s use
Since we are in the IDLE scripting window, let’s pass this into the
So now on line 8, we have
print(my_dog["hungry"]). When we save and run this file, then you see that the output is
True in the left window, which is the value of
You also learned in the last lesson that you can delete a dictionary item with the
del keyword. Let’s take the
and delete it before we call
print(). So when we now run this code, then we get a
KeyError because the key
"hungry" doesn’t exist in the dictionary anymore. To prevent this error from happening, you can check that a key exists in a dictionary with the
Before trying to access the
"hungry" item, you can create an
if "hungry" in my_dog:
print() function call is only executed when
"hungry" is in the
my_dog dictionary. When you run the code now, then no error is raised because Python checked that
"hungry wasn’t in the
my_dog dictionary and didn’t execute the
print() function call.
02:39 Another way of checking if a key exists in a dictionary is looping over it. Looping over a dictionary is a very common practice. You’ll learn more about it in the next lesson.
Become a Member to join the conversation.