A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-dictionary-get-method/ below:

Python Dictionary get() Method - GeeksforGeeks

Python Dictionary get() Method

Last Updated : 01 Aug, 2024

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: 

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. 



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4