Menu Close

Python Dictionary get Method

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 have 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.

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 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 python dictionary get method is:-

dictionary.get(key, value)

Parameter

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 not exist. Default is None.

Return Value

Dictionary get function in Python return value of specified key.

Python Dictionary get Example

Example 1:

Get the value of first_name key using dictionary get python method.

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.get('first_name')
print(result)

Output will be:- Vishvajit

Example 2:

What happen, if the specified value not exist.

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.get('address')
print(result)

Output will be:- None

Example 3:

We can return value for specified key which not exists in the dictionary.

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.get('address', 'Noida')
print(result)

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 tutorial.

Other Dictionary Methods


For more information:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply