Contents
Python dictionary get() method
Python dictionary get() method returns the value corresponding to the specified key.
In this tutorial, you will learn about dictionary get() method in Python, and its usage, with the help of example programs.
Syntax of dict get()
The syntax of dictionary get() method is
dictionary.get(key, value)
Parameters
Parameter | Description |
---|---|
key | Required The key for which value has to be fetched from the dictionary. |
value | Optional If specified key does not exist, get() returns this value. |
Return value
- If the specified key is present, get() returns the corresponding value.
- If the key is not present, and value (second argument) is given, then get() returns this value.
- If the key is not present, and value (second argument) is not given, then get() returns None.
Examples for get() method
1. A simple example for dictionary get() method in Python
In this example, we are given a dictionary in my_dict with some initial key:value pairs. We have to get the value corresponding to the key ‘bar’.
We shall call get() method on the given dictionary object my_dict, and pass the key ‘bar’ as argument.
Since the key ‘bar’ is present in the dictionary, get() method returns the value 14 corresponding to that key.
Output
14
2. Dictionary get() – Key not present
In this example, we try to get the value for a specific key ‘moo’ that is not present in the dictionary.
The key ‘moo’ is not present in the dictionary. Also, we have not given any second argument to get() method for default value. In this kind of scenario, as we have already seen in the “Return value” under “Syntax” section, dictionary get() method returns value None of type NoneType.
Output
None
3. Dictionary get() – Get default value if key not present
You can also tell get() method to return a default value instead of None, if key-value pair is not present for the key specified. Provide the default value as second argument to get() method.
Output
10
dict.get() vs Accessing dict using index
Most of the times, you would see or use indexing style of accessing values of a dictionary with key as index. A sample code snippet is
value_1 = my_dictionary[key_1]
There is a downside of using this style. Which is, when there is no key:value pair for the key we have mentioned, you would get KeyError.
Following is a example demonstrating how using square brackets to get a value corresponding to given key in dictionary ends up with KeyValue error.
Output
Traceback (most recent call last):
File "example.py", line 6, in <module>
print(my_dict['moo'])
KeyError: 'moo'
So, you may have to explicitly check if the key is present, and then access the dictionary using key as index.
Summary
In this tutorial of Python Dictionary Methods, we learned how to use Dictionary get() method to access values when a key is given, with help of well detailed Python programs.