Python Dictionary get() method “returns the value of the specified key if the key is in the dictionary, otherwise it returns None (or a specified default value).“
Syntax
dictionary.get(keyname, value)
Parameters
- The keyname name parameter and the keyname of the item you want to return the value are required.
- The value parameter is Optional. It is the value to return if the specified key does not exist. Default value None.
Return value
Python dictionary.get() method returns:
- The value for the specified key if the key is in the dictionary.
- None if the key is not found and the value is not specified.
- Value if the key is not found and the value is specified.
Visual Representation
Example 1: How to Use Dictionary get() Method
subscription = {
"Netflix": 13,
"Amazon Prime": 9,
"Hulu": "8"
}
print('OTT subscription price:' ,subscription.get("Amazon Prime"))
Output
OTT subscription price: 9
Example 2: When key is not found
subscription = {
"Netflix": 13,
"Amazon Prime": 9,
"Hulu": "8"
}
print('OTT subscription price:' ,subscription.get("HBO Max"))
Output
None
Example 3: Specifying a default value
subscription = {
"Netflix": 13,
"Amazon Prime": 9,
"Hulu": "8"
}
print('OTT subscription price:' ,subscription.get("HBO Max",10))
Output
OTT subscription price: 10
subscription.get(“HBO Max”,10) returns ‘10‘ as a default value since ‘HBO Max‘ is not found.
Example 4: Dict get() method Vs dict[key] to Access Elements
people = {}
print('Age: ', people.get('age'))
print(people['age'])
Output
Age: None
Traceback (most recent call last):
File "/Users/ankitlathiya/Desktop/code/app.py", line 3, in <module>
print(people['age'])
KeyError: 'age'
In the above example, Since the key ‘age‘ is not present in the people dictionary, the get() method returns None.
However, using dict[key] raises a KeyError exception, as the key ‘age‘ is not present in the dictionary.
Thats it.