Hi, friends, Welcome to my new article.
In this article, we’ll be playing around with the .get() method commonly used in Python.
Key Note
As you all know, we use Dictionary to store different elements in Python in the form of key:value pairs, and to access these elements for later use, we use the .get() method. It is just a kind of giving order to the dictionary. Hey, I want this; please serve it.
Syntax of get() method:
dictionary.get(“key”)
Introduction: What is .get() method?
The .get() method is a method with the help of which we can access the elements of the dictionary we have created.
I hope you all are familliar with Python’s Dictionary.
Just like we have the Oxford dictionary, which has two pairs—words and their meanings—similarly, the Python dictionary also has similar pairs, which we call in the Python language—keys and values.
And to access the values of these keys, we use the .get() method.
Here’s a simple example of, how a Python dictionary looks like.
Now let’s get into the dictionary we have created above.
- “Sports” is nothing but the name of the dictionary I have given.
- Cricket, Football, and Tennis are keys, and Virat kohli, Christiano Ronaldo, and Roger Federer are values of the keys, respectively, which we will see how to access when needed by using a simple syntax of the .get() method.
.get() method usage
The get() method returns the value of the asked key which you can store in a new variable for future use.
.get() method : Syntax
dictionary.get(“key”)
Now, let’s simplify the syntax :
Just like how we used to put values in a formula in maths to use it, similarly, we have to put values here as well.
In place of dictionary, type the name of the dictionary which is “sports”,
Then, the name of the method as it is .get() and
Lastly, in place of Key, type the name of the Key which you want to return, let’s say “Cricket”
Here is what it look likes after:
batsman = sports.get(“Cricket”)
How to use .get() method?
Example
Let’s use the .get() method to access the values of each key from sports (dict).
- To access the value of Cricket
I’ll run simple code –
batsman = sports.get(“Cricket”)
And, simultaneously, I’ll also store the output in a new variable named batsman.
Here is how the code looks like
Now you may ask; why we are storing the output in a new variable.
Simply because, It makes the values easily accessible for further use, enhances reusability, and reduces redundancies from the code.
For example, here we have stored the output in a new variable batsman, which means we have stored the value of Cricket in a variable batsman.
Now whenever we feel the need to use the value of Cricket, I can simply access it by using a variable batsman rather than typing the whole .get() method syntax again and again.
- Now let’s try to access the value of “Football.”
Again, the code is almost similar to how it was in the above step; however, some minor changes need to be considered.
The name of the dictionary will remain the same, i.e., sports; however, the name of the key will change as per requirements. In the first step, it was “Cricket,” now it will be “Football.”
Lastly, we need to create a new variable where this output can be stored for further use. I’ll name that variable “best_footballer.”.
So, this is how our code will look like:
best_footballer = sports.get(“Football”)
print(best_footballer)
The output which you’ll get here is = Christiano Ronaldo.
- To access the value of “Tennis”
I’ll create a variable to store the output and then simply gonna use the .get() method.
Let the variable here be – rf_tennis, where rf is nothing but the short form of Roger Federer.
Then our code becomes,
rf_tennis = sports.get(“Tennis”)
print(rf_tennis)
This is how we use the .get() method to fetch the values of particular keys from the respective dictionary.
However, you can also access the values without using the get method, in which we only use the name of the dictionary and key. The method is known as the direct key method.
Syntax of direct key method is
variable = dictionary[“Key”]
print(variable)
For example, let’s try to fetch the value of “Cricket” from our dictionary by using a direct method. So its code will be as follows:
batsman = sports[“Cricket”]
Even though both methods return the same result, programmers still prefer to go with the .get() method due to its error handling feature, which we will discuss later in this article
Python .get() method vs dict[Key] method
Well, as we have seen both these methods give the same result in return, then what’s the difference between the two?
Why do programmers prefer the .get() method over the dict[Key] method? Let’s find it out.
The answer is— .get() methods error handling capacity. It does not let the computer raise an error and stop our code from execution. Let’s see how it works.
There’s something special to know about get(): That is, it returns a default value (None) if the key is missing or not found.
For example:
In our sports dictionary, we had three keys: Cricket, Football, and Tennis. When we tried to fetch the values using the .get() method, it was easily accessible without any complication. Right?
But, what if we try to access the value of a key that isn’t present in our dictionary? For instance, let’s try to access the value of Chess.
In this case for Chess, the get() method will return None in output, saying; Bro, The key you’re looking for doesn’t exist in the dictionary, rather than throwing an error.
Therefore, our program will still be working seamlessly.
However, this won’t be the same if we try to access the value of Chess using the dict[“Key”] method. It will raise an error without showing any mercy, and from there onward our program will stop running.
That’s why programmers choose get() over the dict[“Key”] method.
Yeah, there can be some more reasons also, but this was one I knew and must be known to every Python programmer.
Benefits of .get() method
- Prevents from error to raise.
As we have seen, it returns the default value (None) as output when we ask for a key that is not in our dictionary. So there is no question of an error being raised.
- Saves Time and Energy
You know very well how it feels when errors occur while programming. If the program is small, then it’s manageable; we can easily grab where the error has occurred, but finding errors in a large program and correcting them is a different thrill, which no programmer would like to experience.
In such a situation, the get() method plays an important role to some extent in preventing errors raised by missing keys.
Now you must be asking, What is this matter of missing key or key not found?
Why would a programmer want to access the value of a key that does not even exist in the dictionary? Has he gone mad? No! It’s not how it seems to be!
You know that Python is a case-sensitive language. In which Apple is not equal to Apple (difference capital A & small a)
If the programmer mistakenly types the name of the keys in the wrong case while accessing it or makes a spelling mistake, then the error of missing key will definitely be raised. Thankfully, it gets prevented by using the .get() method.
Usefull Links
Want to learn more about dictionaries in Python? Then there’s a YouTube video from Telusko you should definitely watch.
From creating dictionaries to playing around by using different techniques, he shares absolutely everything you must know.