From the course: Programming Foundations: Data Structures

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Handle missing dictionary keys

Handle missing dictionary keys

- [Instructor] When accessing dictionary keys, you may encounter situations where the specified key doesn't exist. Trying to access a missing key directly will raise a key error, potentially causing your program to crash if it's not handled properly. Take this example of employee salaries. Let's try to access a salary for an employee who isn't in the dictionary, say Charlie. Since Charlie isn't in the dictionary, this will raise a key error. And that's what we get in the console. To handle missing keys more gracefully, a common method is to use the GET function. This allows you to try retrieving a value for a given key while providing a default value if the key doesn't exist. This prevents any error from being raised. Let's try accessing the Charlie key using GET. If Charlie's not found, we'll return not found. Let's run it. Instead of throwing an error, the GET method returns not found. Now another approach is to use a try-except block to catch the key error. This can be useful if…

Contents