Safely Checking for Key Existence in a Dictionary
In this lesson, we will explore the get()
method used to check for the existence of keys in a dictionary.
The get()
function accepts two parameters.
The first parameter is the key you want to search for, and the second parameter is the default value to return if the key does not exist.
Parameter
: A variable that handles the values passed to a function.
my_dict = {'name': 'CodeBuddies', 'age': 30} country = my_dict.get('country', 'Not Found') # Since the 'country' key is absent, it returns the default value 'Not Found' print(country)
If no default value is provided as the second argument, the method returns None
when the specified key does not exist.
my_dict = {'name': 'CodeBuddies', 'age': 30} country = my_dict.get('country') # Since the 'country' key is absent, it returns the default value 'None' print(country)
In the code above, we used the get
function to search for the country
key.
However, since the country
key does not exist in the dictionary, the get
method returns to its default value of None
.
What value is returned by the get()
method if no default value is set?
Unknown
Undefined
None
Null
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result