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 you do not provide a default value as the second argument, it will return None
when the key you are searching for 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 its default value of None
.
What value is returned by the get()
method if no default value is set?
Unknown
Undefined
None
Null
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result