Python Dictionary get() Method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).
Python Dictionary get() Method Syntax:
Syntax : Dict.get(key, default=None)
Parameters:
- key: The key name of the item you want to return the value from
- Value: (Optional) Value to be returned if the key is not found. The default value is None.
Returns: Returns the value of the item with the specified key or the default value.
Python Dictionary get() Method Example:
Python3
d = { 'coding' : 'good' , 'thinking' : 'better' } print (d.get( 'coding' )) |
Output:
good
Example 1: Python get() Method with default parameter.
Python
d = { 1 : '001' , 2 : '010' , 3 : '011' } # since 4 is not in keys, it'll print "Not found" print (d.get( 4 , "Not found" )) |
Output:
Not found
Example 2: Python Dictionary get() method chained
The get() to check and assign in absence of value to achieve this particular task. Just returns an empty Python dict() if any key is not present.
Python3
test_dict = { 'Gfg' : { 'is' : 'best' }} # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # using nested get() # Safe access nested dictionary key res = test_dict.get( 'Gfg' , {}).get( 'is' ) # printing result print ( "The nested safely accessed value is : " + str (res)) |
Output:
The original dictionary is : {'Gfg': {'is': 'best'}} The nested safely accessed value is : best
Time complexity: O(1) because it uses the get() method of dictionaries which has a constant time complexity for average and worst cases.
Auxiliary space: O(1) because it uses a constant amount of additional memory to store the dictionary and the string values.