Python Dictionary get() Function
The Dictionary get() method retrieves the value for a given key.
If the key is found in the dictionary, the method returns its corresponding value. If the key is not found, the method returns a default value if provided. If default value is not specified, it returns None.
Therefore, this method never raises a KeyError exception.
Syntax
my_dictionary.get(key, default)
get() Parameters
Python Dictionary get() method parameters:
| Parameter | Condition | Description |
|---|---|---|
key | Required | The key to be searched in the dictionary. |
default | Optional | The value to return if the key is not found. The default value is None. |
get() Return Value
Python Dictionary get() function returns:
- the value for the specified
keyifkeyis in the dictionary. Noneif thekeyis not found andvalueis not specified.valueif thekeyis not found andvalueis specified.
Examples
Example 1: Basic Usage of get() method of dictionaries
The get() method is used to get the value for the specific key.
my_dict = {'name': 'Tom', 'age': 25}
my_value = my_dict.get('name')
print(my_value) # Output: Tom
output
Tom
If key is not in the dictionary, the method returns None.
my_dict = {'name': 'Tom', 'age': 25}
my_value = my_dict.get('job')
print(my_value) # Output: None
output
None
Example 2: get() with Default Value Parameter
If you want a value different from None to be returned, you have to specify the default parameter.
If key is in the dictionary, the method returns the value for key (no matter what you pass in as default, since a pair key-value exists in the dictionary!).
my_dict = {'name': 'Tom', 'age': 25, 'job': 'Manager'}
my_value = my_dict.get('job', 'Developer') # get with default value 'Developer'
print(my_value) # Output: Manager
output
Manager
But if key is not in the dictionary, the method returns specified default.
my_dict = {'name': 'Tom', 'age': 25}
my_value = my_dict.get('job','Developer') # get with default value 'Developer'
print(my_value) # Output: Developer
output
Developer
Example 3: get() Method vs Dictionary Indexing (Square Bracket Notation)
The get() method is similar to indexing a dictionary by key in that it returns the value for the specified key.
However, if you refer to a key that is not in the dictionary, get() method will NEVER raise a KeyError.
For example, if the key is present in the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
print(my_dict.get('name')) # Output of get: Tom
print(my_dict['name']) # Output of indexing: Tom
output
Tom
Tom
For example, if the key is not present in the dictionary:
my_dict = {'name': 'Tom', 'age': 25}
print(my_dict.get('job')) # Output of get: None
print(my_dict['job']) # Raises KeyError: 'job'
output
None
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(my_dict['job'])
KeyError: 'job'