The get()
method in Python dictionaries is used to retrieve the value associated with a specified key. It allows you to access the value corresponding to the given key, similar to dictionary indexing, but with the added benefit that it won't raise a KeyError
if the key is not found in the dictionary. Instead, it will return a default value that you can specify as an argument. If the key is not found and no default value is provided, it will return None
by default.
get()
method:
value = dictionary.get(key, default)
key
: The key whose value you want to retrieve from the dictionary.default
: (Optional) The default value to be returned if the specified key is not found in the dictionary. If not provided, it defaults to None
.Now, let's see some examples:
get()
to retrieve a value from the dictionary
# Sample dictionary
fruit_dict = {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}
# Retrieve the value associated with the key 'banana'
result = fruit_dict.get('banana')
# Print the result
print(result)
yellow
In this example, the get()
method successfully retrieved the value 'yellow'
associated with the key 'banana'
from the fruit_dict
.
# Sample dictionary
fruit_dict = {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}
# Try to retrieve the value associated with the key 'grape'
# As 'grape' key is not present, it will return the default value 'unknown'
result = fruit_dict.get('grape', 'unknown')
# Print the result
print(result)
unknown
In this example, the get()
method attempted to retrieve the value associated with the key 'grape'
, which is not present in the fruit_dict
. Since a default value 'unknown'
is provided, it returns 'unknown'
.
# Sample dictionary
fruit_dict = {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}
# Try to retrieve the value associated with the key 'watermelon'
# As 'watermelon' key is not present, it will return None (default value)
result = fruit_dict.get('watermelon')
# Print the result
print(result)
None
In this example, the get()
method attempted to retrieve the value associated with the key 'watermelon'
, which is not present in the fruit_dict
. Since no default value is provided, it returns None
by default.
Using the get()
method is a safer way to access dictionary values, especially when you are uncertain whether a key exists in the dictionary or not, as it avoids raising a KeyError
.