get()in Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

The get() method in Python is used to fetch the value of a key from a dictionary. If the key is not present in the dictionary then it simply returns a None. However, we can also pass a default value (optionally) to the get() method in Python. In case the key is not present in our dictionary then this optional default value is returned. In this article, we will learn about the get() method in Python, along with its usage and code examples.

Syntax of get() Method in Python

The syntax of the get() method in Python is given below :

Syntax of get():

So, in the get() method in Python, we write our dictionary name, followed by a dot('.') operator and the get() method. The get() method takes two parameters - the key and the value. Let us also learn about the different parameters taken by the get() method in Python.

Parameters of get() in Python

As we saw in the above syntax, the get() method in Python takes a key and an optional value. Let us learn about each of them in detail:

PARAMETERS OF FUNCTION

  1. key : The key is a mandatory parameter that is passed to the get() method in Python. It is basically the name of the key for which we are searching the corresponding value from the dictionary. There is a possibility that no such key can exist in the dictionary. In that case, our get() method in Python simply returns a None.
  2. value : The value is an optional parameter that is passed to the get() method in Python. In some cases, we might not have the specified or mentioned key in our dictionary. In those cases, we can also pass a value optionally to be returned if no such key exists in the dictionary. Finally, the default value we have passed as the 2nd parameter of the get() method is returned from our get() method.

Return Values of get() in Python

There are three cases when it comes to the return values of get() method in Python. Let us discuss each of them:

  1. The key already exists in the dictionary: If the key passed to the get() method already exists in the dictionary, then the key's corresponding value is simply returned by the get() method in Python.
  2. The key does not exist in the dictionary: If the key passed to the get() method does not exist in the dictionary, then None is returned by the get() method in Python. This adds many benefits to the () method since no error is thrown even if we are trying to access a key that does not exist. We also do not have any additional overhead of putting any checks in the dictionary.
  3. We have passed an optional value to get(): Suppose, while fetching any value from the dictionary we have also passed any optional "value" to the get() method. In that case, if the key does not exists then that particular optional value is returned. In simple words, if we do not have that particular key in our dictionary, then instead of returning a None, the get() method returns the optional value passed to it in the parameter.

Basic Example of get() Method in Python

Now that we have a basic understanding of how the get() method works in Python, let us take a look at a very basic example of the get() method in Python.

Example 1: In this example, we will create a dictionary of items (as keys) and their prices (as values). And then, using the get method, we will try to fetch the value of the price corresponding to the items (keys).

Code :

Output :

Explanation: In the above example, we are trying to fetch the price of the water bottle. For that, we simply used the get() method in Python. We applied the get() method over the dictionary items_list and, passed 'Water Bottle' as the key. And, after that, we have assigned the corresponding result to our variable. Please note, that since the key exists in the dictionary, we will get our corresponding value from the get() method.

What is get() Method in Python ?

Suppose you are handling a dictionary in Python that is getting its value from a certain web API. Now, there are equal chances of getting the value corresponding to some key in your dictionary, and not getting any value. So, for this case you will have to do the extra effort of putting if-else checks in your code, that will confirm the existence of the key. In some cases, you might also have to put your code into try-except blocks to prevent any probable errors (due to unavailable keys).

To solve all the issues stated above, we have got the get() method in Python. Since we have already learned about it in detail above, let us now formally define the get() method in Python.

DEFINITION

The get() method is a method from the dictionary class in Python, that is used to fetch the value corresponding to a key in the dictionary in Python.

FETCHING VALUES

In the above scenario (as per the image), suppose when we do not pass any default value to get() method in Python, then if it gets the key it returns the associated value with it. Otherwise, a None is returned.

FETCHING VALUE WITH DEFAULT VALUE

In the above scenario (as per the image), suppose when we pass any default value to get() method in Python, then if it gets the key it returns the associated value with it. Otherwise, the default value is returned.

Takeaway: Basically the dic.get(specifiedKey) searches the dictionary dic, for the specifiedKey and returns the corresponding value in case it is found. If the key is not found, it simply returns a None. And, if we have specified a default value, then it returns that in absence of the key in the dictionary.

Examples of get() Method in Python

Now, let us see various examples covering all the corner cases related to the get method in Python.

Example 1: Trying to Fetch the Value of an Item that does not Exist

In this example, we will try to fetch the value of an item, that does not exist in our dictionary. So for this, we will take our previous example (discussed above) where we had a dictionary of items (as the keys) and their prices (as their values). Let us look into the code of the same:

Code :

Output :

Explanation : In our above example, we are trying to fetch the price of the item - pen. But, as you can see, there is no item called "pen" in our dictionary items_list. Since the key is not present in our dictionary, as we already learned above, the get() method in Python will simply return a None, instead of raising an error.

Note: Please note that we have not passed any default value to our get() method, otherwise that would have been returned in this case.

Example 2: Dictionary get() – With a Default Value

In the above example, we did not pass any default value to our get() method in Python. That was the reason we were getting None as the result. Now, in this example, we will be passing a default value to our get() method. Let us look into the code of the same:

Code :

Output:

Explanation: As you can see through the above example, we have again tried to fetch the value of the item pen that does not exist in our dictionary. But there is one exception in this example, that is, we have also passed the default price of the item as the second argument in our get() method.

Hence, after fetching the item's value, we get the default value(we passed to get()) as our result and not None. This is also a significant advantage of using the get() method in Python over the normal indexing.

Example 3: Dictionary get() – With a Default Value and Key Exists

Have you ever wondered what will happen if the key exists in the dictionary and we have also passed a default value to our get() method in Python? This example will demonstrate that case.

Let us look at the example below to understand it better.

Code :

Output:

Explanation: In the above example, you can see that we are trying to fetch the value of an item that already exists in the dictionary. Also, we have passed a default value for the same. In the result, as you can see, our output is the original value of the item (and not the default value).

So, you can conclude that, if we try to access the value of a key that exists in the dictionary, then we will get the original value, it does not matters whether we have passed the default value or not.

Example 4: Key not Present in the Dictionary

Let us now take an example where the key will not be present in the dictionary.

Code :

Output:

Explanation:

In the above example, we have considered two scenarios. They are as stated below:

  1. Key is not present and No default value given: In that case simply None is returned by our get() method in Python.
  2. Key is not present and default value given: In that case simply the default value (that is 1.0) is returned by our get() method in Python.

Example 5: Python get() Method Vs dict[key] to Access Elements

Let us now see the difference between accessing the elements using Python's get() method vs the regular dict[key].

Code :

Output :

Explanation: So, in the above example, we have tried to access the key with the name " pages". We can already see, that there is no key named "pages" in our records dictionary. But, by using the indexing method, that is, records[pages], we see that a KeyError: 'pages' is thrown. This is the real issue that is faced while using indexing to fetch elements.

However, this can be solved using the get() method. Let us see how.

Code :

Output:

Explanation: So, this issue is easily tackled by the get() method. We did not get any error, instead, we got None as the result if the key is absent. Also, as we learned above, we can also pass a default value, which is returned if the key is not present.

We will learn about the difference between indexing and the get() method in detail ahead in the article.

Accessing Values of Dictionary Using get() VS Indexing (dict[key])

We have seen quite a lot of examples of the get() method in Python. And, you must be aware of accessing the value of a dictionary using indexing. For a recap, consider the example below which fetches the value using indexing in the dictionary.

Code :

Output :

Explanation: In the above example, we are trying to fetch the value of b, from the dictionary. For that, we have used indexing to fetch its value. We have simply passed the key into the index of our dictionary. Finally, we have got our expected result.

Now, you must be wondering, what is the point of using the get() method in Python, when we can already use the indexing? So, let us take another example to answer your question.

Code :

Output :

Explanation: Did you see it? We directly got an error when we tried to access the value of an item that does not exist in our dictionary. So, this is the basic flaw that comes with using indexing to fetch the values of keys in the dictionary in Python. Here comes the get() method which has the greatest advantage of handling this smoothly without encountering any error. Let us try the same code using the get() method in Python.

Code :

Output :

Explanation : Now, when we used the get() method, then we directly passed the default value with it. And, you can see how efficiently our get() method handled this issue. So, we got our default value in the result (since the key is not present in the dictionary), and prevented any error.

Takeaway: Whenever you are uncertain about the presence of a key in the dictionary, usage of the get() method is always preferable over the normal indexing.

Conclusion

In this article, we learned about the get() method in Python. Let us now take a brief pause and reflect on what we studied throughout.

  • get() method in Python is used to get the value of any specified key from a dictionary.
  • The get() method returns the value of the key if the key is present in the dictionary.
  • The get() method returns a None if the value is not present in the dictionary.
  • However, if we specify a default value, then the default value is returned by get() (instead of None) in case of the absence of the key.
  • The greatest advantage of the get() method in Python is that it does not throw an error, irrespective of the presence/absence of the key in the dictionary.
  • Using the get() method is always preferable over indexing to fetch values when we are uncertain of the presence of the key in the dictionary.

See Also

Now that you have learned well about the get() method in Python, I would highly recommend you to go ahead and pick one of these scaler articles below for further learning: