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
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 |
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 |
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
myDictionary = {
'fo':12,
'br':14
}
#key not present in dictionary
print(myDictionary.get('moo'))
Output:
None
myDictionary = {
'fo':12,
'br':14
}
print(myDictionary.get('moo', 50))
Output:
50
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'