Python Dictionary get()
The dict.get()
method returns the value of the specified key.
Syntax:
dict.get(key, value)
Parameters:
- key: (Required) The key to be searched in the dictionary.
- value: (Optional) The value that should be returned, in case the key is not found. By default, it is None.
Return Value:
Returns the value of the specified key if a key exists in the dictionary. If a key is not found, then it returns None. If a key is not found, and the value parameter is specified, it will return the specified value.
The following example demonstrates the dict.get()
method.
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.get('I')
print("I = ",value)
I = 1
If the key is not found in the dictionary, and the value parameter is not specified, it will return None.
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.get('VI')
print("VI = ", value)
VI = None
If the key is not found in the dictionary and the value parameter is specified, it will return the specified value.
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.get('VI','Not in the dictionary.')
print("VI = ", value)
VI = Not Found