Python Dictionary get()

The dict.get() method returns the value of the specified key.

Syntax:

dict.get(key, value)

Parameters:

  1. key: (Required) The key to be searched in the dictionary.
  2. 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.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.get('I')
print("I = ",value)
Output
I = 1

If the key is not found in the dictionary, and the value parameter is not specified, it will return None.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.get('VI')
print("VI = ", value)
Output
VI = None

If the key is not found in the dictionary and the value parameter is specified, it will return the specified value.

Example:
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
value = romanNums.get('VI','Not in the dictionary.')
print("VI = ", value)
Output
VI = Not Found