In this dictionary method article, we are going to learn all about the Python dictionary get method to get the value of the specified key. In the previous tutorial, we learned the python dictionary fromkeys method to create the new Python dictionary.
To understand this example, you should have basic knowledge of the Python dictionary.
Headings of Contents
Python Dictionary get Method
Python dictionary get method is a pre-defined dictionary method, that is used to get the value of the specified key.
If the specified key is not present in the dictionary, it will return None. You can also return a value for the key which not exist in the dictionary.
Syntax
The syntax of the python dictionary get method is:-
dictionary.get(key, value)
Parameter
The dictionary get function in Python accepts two parameters.
- key:- Required, key name of the item to return the value from.
- value:- Optional, A value to be returned, if the specified key does not exist. Default is None.
Return Value
Dictionary gets to function in Python return value of the specified key.
Python Dictionary get Example
Example 1:
Get the value of the first_name key using the dictionary get python method.
Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.get('first_name')
print(result)
The output will be:- Vishvajit
Example 2:
What happens, if the specified value does not exist.
Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.get('address')
print(result)
The output will be:- None
Example 3:
We can return a value for the specified key which not exist in the dictionary.
Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.get('address', 'Noida')
print(result)
The output will be:- Noida
Conclusion
In this guide, you have seen all about the dictionary get method to access the value of the specified key in the dictionary.
If this article helped you, please continue visiting for further interesting python tutorials.
Other Dictionary Methods
For more information:- Click Here