In this article, we’ll learn what Python dictionary get method is and how to use it to fetch data from dictionaries.
A proper step by step explanation of multiple practical code examples will be provided to better understand how Python dictionary get method works.
After reading this post, you’ll have a thorough understanding of how to properly use get method of Python dictionary.
- What is Python Dictionary Get Method?
- Syntax of Get Method
- Implementing Python Dictionary Get Method (Multiple Examples)
- Example 1: Fetch Data From Dictionary using Get Method
- Example 2: When Key is not Available in Dictionary
What is Python Dictionary Get Method?
This method is used to get a specific value from dictionary using a key assigned to it. We’ll also see what it’ll return if the specified key is not present in dictionary.
Let’s now understand Python dictionary get method practically using proper examples. But first, let’s go through its syntax.
Syntax of Get Method
Get method takes two arguments. Key is the key item of dictionary that is to be searched and if found, then it’ll return the value specified to it.
Value is optional. If the key is not found in dictionary and if the value is specified, then this value will be returned. If not, then None will be returned.
Implementing Python Dictionary Get Method (Multiple Examples)
Below examples will practically demonstrate how Python dictionary get method works.
Example 1: Fetch Data From Dictionary using Get Method
We’ve successfully fetched the value of key b.
Let’s look at how to fetched a nested list.
[3.5, 'purple', 34, 22.7]
You can try it with other datatypes as well like tuples, sets, strings etc.
Example 2: When Key is not Available in Dictionary
Let’s now see what happens when the specified key is not present in dictionary. See below code:
It returns none if the specified key is not found in dictionary. But if you want to return a custom value then see below code:
print(dictItems.get('name',34)) // it will return 34 if the key is not found
You can return value of other datatypes as well like list, tuple, set or string etc.
Reason for using the get method is that it will return none or we can specify a custom value to be returned if the specified key is not found in dictionary. But if we use the brackets method like dictName[‘keyname’] then it’ll give a key error is the key if not found.
So this is how you can easily use Python dictionary get method to fetch data from dictionary.
Don’t hesitate to ask questions regarding the implementation of Python dictionary get method, if you still have any. I’ll be very delighted to answer all.
In conclusion, hope you now have a proper and in-depth practical knowledge of how to use Python dictionary get method. I’ll be looking forward at your comments on this post. Thank you for reading it.