Python Dictionary get Function

Python Dictionary get function is used to return value at a given key position. In this section, we discuss how to use this Dictionary get function. The syntax behind this Python dict get function is:

dictionary_name.get(key, default_value)

Python Dictionary get Example

The Python dict get function returns the value at the specified user key.

TIP: Please refer to the Dictionary in Python.

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items: ", myDict)

print("\nValue of Key 2  :  ",  myDict.get(2))
print("Value of Key 3  :  ",  myDict.get(3))
print("Value of Key 4  :  ",  myDict.get(4))
print("Value of Key 1  :  ",  myDict.get(1))
Python Dictionary get Example 1

In this Python dict get program, we are using the second argument to display the default value. First, we are trying to access the non-exiting dict key. As you can see, it returns None because key is not present.

However, you can use the second argument to specify the default value for non-existing values. Here, the last line of code searched in the dictionary and returns default value Mango.

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Items: ", myDict)

print("\nValue of Key 4  :  ",  myDict.get(4))
print("Value of Key 5  :  ",  myDict.get(5))

print("\nValue of Key 6  :  ",  myDict.get(6))
print("Value of Key 6  :  ",  myDict.get(6, 'Mango'))
Items:  {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}

Value of Key 4  :   Kiwi
Value of Key 5  :   None

Value of Key 6  :   None
Value of Key 6  :   Mango