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.
Parameters of the get() 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.
Example of Missing Key
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
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.