Get() method for dictionaries in Python



Get() method for dictionaries in Python

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)

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

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

 

Last Updated on October 28, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs