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 one and the syntax behind this Python dictionary get function is:

diName.get(key, default_value)

Python Dictionary get Example

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

TIP: Please refer to the Dict in Python.

Python Dictionary get Example 1

In this 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 word Mango.

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

print("\nKey 4  :  ",  myDi.get(4))
print("Key 5  :  ",  myDi.get(5))

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

Key 4  :   Kiwi
Key 5  :   None

Key 6  :   None
Key 6  :   Mango