Check with get() Method
In this step, you will learn how to use the get()
method to access dictionary values safely. The get()
method provides a way to retrieve a value associated with a key, and it allows you to specify a default value to return if the key does not exist. This prevents your program from crashing due to KeyError
exceptions.
Let's continue using the dictionary we created in the previous steps. If you don't have the dictionary_keys.py
file, create it again in the ~/project
directory with the following content:
## Content of dictionary_keys.py
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Now, let's use the get()
method to retrieve the value associated with the key "name"
. Add the following code to your dictionary_keys.py
file:
## Content of dictionary_keys.py
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
name = my_dict.get("name")
print(name)
Save the file and run the script using the following command in the terminal:
python dictionary_keys.py
You should see the following output:
Alice
The get()
method successfully retrieved the value associated with the key "name"
.
Now, let's try to retrieve the value associated with a key that does not exist, such as "country"
. Modify your dictionary_keys.py
file as follows:
## Content of dictionary_keys.py
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
country = my_dict.get("country")
print(country)
Save the file and run the script again:
python dictionary_keys.py
The output will be:
None
By default, the get()
method returns None
if the key does not exist. This prevents a KeyError
from being raised.
You can also specify a default value to be returned if the key does not exist. Modify your dictionary_keys.py
file as follows:
## Content of dictionary_keys.py
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
country = my_dict.get("country", "Unknown")
print(country)
Save the file and run the script:
python dictionary_keys.py
The output will be:
Unknown
In this case, since the key "country"
does not exist in the dictionary, the get()
method returned the default value "Unknown"
that we specified.
Using the get()
method is a best practice when working with dictionaries, as it allows you to handle cases where a key might not exist gracefully, preventing errors and making your code more robust.