Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Get() method for dictionaries in Python

  • Difficulty Level : Easy
  • Last Updated : 05 Oct, 2021

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

Syntax : Dict.get(key, default=None)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Parameters: 



  • key: The keyname 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.

Python Dictionary get() method example

Example 1: Python get() method work for dictionaries

Python




dic = {"A": 1, "B": 2}
print(dic.get("A"))
print(dic.get("C"))
print(dic.get("C", "Not Found ! "))

Output: 

1
None
Not Found !

Example 2: Python Dictionary get() method nested

The get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present.

Python3




# Python3 code to demonstrate working of
# Safe access nested dictionary key
# Using nested get()
   
# initializing dictionary
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

This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!