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 - Python Tutorial
From the course: Programming Foundations: Data Structures
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
-
-
-
-
-
What is a dictionary?1m 23s
-
Create a dictionary in Python1m 40s
-
(Locked)
Mutate a dictionary in Python3m 5s
-
(Locked)
Solution: Update salary53s
-
(Locked)
Handle missing dictionary keys2m 2s
-
(Locked)
Retrieve keys and value collections from dictionaries1m 44s
-
(Locked)
Solution: Clean user preferences1m 27s
-
(Locked)
When to use dictionaries1m 22s
-
-
-
-
-
-
-