Python get() Function
The get() function in Python is used when we need to get the value of any item in a dictionary with the specified key. For example:
x = {"Day": "Mon", "Month": "Nov", "Year": "2021"}
print(x.get("Year"))
The output will be:
Python get() Function Syntax
The syntax of get() function in Python, is:
dictionary.get(key, default)
where default parameter is used when we need to provide the default value, in case if the specified key does not exists in the given dictionary. The default parameter is optional.
Note: The default value of default parameter is None. Means that, if the default parameter is not given, and the specified key is not available in the dictionary, the get() will return None.
Python get() Function Example
Here is an example of get() function in Python:
x = {"Day": "Mon", "Month": "Nov", "Year": "2021"}
val = x.get("Month", "Not Found!")
print(val)
The output will be:
Let's replace the following statement:
val = x.get("Month", "Not Found!")
with the statement given below:
val = x.get("Date", "Not Found!")
Now the output will be:
The default parameter can also be used to give some default value when the given key does not exists in the dictionary. Like when working with prices of some items using dictionary, and the program needs to be created in a way to give some default price if the given item is not available in dictionary. It depends on the programmer how they utilize the get() method.
« Previous Function Next Function »
Liked this post? Share it!