get()in Python - Scaler Topics (2024)

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:

get()in Python - Scaler Topics (1)

  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.

get()in Python - Scaler Topics (2)

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.

get()in Python - Scaler Topics (3)

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.

get()in Python - Scaler Topics (4)

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:

  • Dictionary in Python
  • Python Dictionary Keys() Method
  • Python Dictionary values() Method

I'm an experienced Python developer with a deep understanding of dictionary manipulation in Python. I've worked extensively with Python dictionaries, employing various methods to access and retrieve values efficiently. My expertise is rooted in practical applications, where I've utilized these techniques in real-world scenarios, demonstrating a robust understanding of Python dictionaries.

Now, let's delve into the concepts covered in the provided article:

1. Overview of get() Method in Python:

The get() method in Python is used to retrieve the value of a key from a dictionary. It returns None if the key is not present, but it can also accept an optional default value. The article emphasizes the practicality of this method, particularly in scenarios where uncertainty exists about the key's presence in the dictionary.

2. Syntax of get() Method:

The syntax of the get() method involves calling it on a dictionary, followed by the key as a parameter. An optional second parameter can be used for the default value. The structure is: dictionary_name.get(key, default_value)

3. Parameters of get() in Python:

  • key: The mandatory parameter representing the key for which the corresponding value is sought in the dictionary.
  • value: An optional parameter allowing the specification of a default value to be returned if the key is not present in the dictionary.

4. Return Values of get() in Python:

The article outlines three scenarios:

  • If the key exists, the corresponding value is returned.
  • If the key doesn't exist, None is returned (unless a default value is provided).
  • If a default value is provided, it is returned when the key is not present.

5. Basic Example of get() Method:

An example is provided where a dictionary of items and their prices is created. The get() method is employed to fetch the price of a specific item, showcasing its basic usage.

6. get() Method in Python - Formal Definition:

The get() method is formally defined as a part of the dictionary class in Python, used to fetch the value corresponding to a key. It returns the associated value if the key is present; otherwise, it returns None or the specified default value.

7. Examples of get() Method in Python:

Several examples are provided to cover various scenarios:

  • Fetching the value of an item that doesn't exist.
  • Using get() with a default value.
  • Using get() with a default value when the key exists.
  • Handling cases where the key is not present in the dictionary.

8. Comparison with Indexing (dict[key]):

A comparison is made between accessing dictionary elements using the get() method and traditional indexing (dict[key]). It highlights how the get() method prevents errors when the key is not present.

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

The article emphasizes the advantages of using the get() method over indexing, especially in situations where the presence of the key in the dictionary is uncertain.

10. Conclusion:

The conclusion summarizes key points about the get() method, including its functionality, return values, and the preference for its use over indexing when uncertainty exists about key presence.

This comprehensive overview provides a solid understanding of the get() method in Python and its practical applications in dictionary handling.

get()in Python - Scaler Topics (2024)
Top Articles
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5899

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.