Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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.

00:14 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 "name", "age", and "nicknames". I also added the fourth key, "hungry" with the value True again.

00:34 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 "hungry".

00:50 Since we are in the IDLE scripting window, let’s pass this into the print() function.

01:03 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 "hungry".

01:20 You also learned in the last lesson that you can delete a dictionary item with the del keyword. Let’s take the my_dog["hungry"] item

01:31 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 in keyword.

01:53 Before trying to access the "hungry" item, you can create an if statement: if "hungry" in my_dog: print(my_dog["hungry"]).

02:20 So 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.

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.