Open In App

Python Dictionary get() Method

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python Dictionary get() Method returns 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, Value)

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

Python
d = {'coding': 'good', 'thinking': 'better'}
print(d.get('coding'))

Output:

good

Example 1: Python get() Method with Second Parameter

Here, In the code 4 is not in keys, so the second parameter will print “Not found”.

Python
d = {1: '001', 2: '010', 3: '011'}

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.

Python
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. 


Next Article
Article Tags :
Practice Tags :

Similar Reads