Tutorial Study Image

Python get()

The get() function in python helps to return the value of the specified key if it was in the dictionary. If the key does not exist the specified value is returned, in default it is none.


dict.get(key[, value])  #where key is the item to be searched
 

get() Parameters:

This method takes two parameters. If we use dict[key] and the key is not found then, the KeyError exception is raised.

Parameter Description Required / Optional
key  key to be searched in the dictionary Required
value Value to be returned if the key is not found. The default value is None Optional

get() Return Value

We can use get() instead of dict() to avoid the KeyError exception because of its default value.

Input Return Value
key in a dictionary the value for the specified key
key is not found and value is not specified None
key is not found and value is specified given value

Examples of get() method in Python

Example 1: How get() works for dictionaries in Python?


persondet = {'name': 'Jhon', 'age': 35}

print('Name: ', persondet.get('name'))
print('Age: ', persondet.get('age'))

# value is not provided
print('Salary: ', persondet.get('salary'))

# value is provided
print('Salary: ', persondet.get('salary', 5000))
 

Output:


Name:  Jhon
Age:  35
Salary:  None
Salary:  5000

Example 2:Python dictionary get() – Key not Present


myDictionary = {
 'fo':12,
 'br':14
}

#key not present in dictionary
print(myDictionary.get('moo'))
 

Output:


None

Example 3:Python dictionary get() – With Default Value


myDictionary = {
 'fo':12,
 'br':14
}

print(myDictionary.get('moo', 50))
 

Output:


50

Example 4:Python get() method Vs dict[key] to Access Elements


persondet = {}

# Using get() results in None
print('Salary: ', persondet.get('salary'))

# Using [] results in KeyError
print(persondet['salary'])
 

Output:


Salary:  None
Traceback (most recent call last):
  File "", line 7, in 
    print(persondet['salary'])
KeyError: 'salary'