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
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
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.
Become a Member to join the conversation.