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.

# Python Dictionary get Example

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

# Get Value
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

Python dict get Example 2

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 key. As you can see, it returns None. However, you can use the second argument to specify the default value for non-existing values. Here, the last line of code returns Mango as the default value.

# Python Dictionary get Example

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

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

# Get Value with Default Value
print("\nValue of Key 6  :  ",  myDict.get(6))
print("Value of Key 6  :  ",  myDict.get(6, 'Mango'))
Dictionary 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