Python Dictionary get() Method Tutorial

Python dictionary data type provides the get() method in order to return a specified item in a dictionary. As dictionary items are consist of key-value pairs generally the key is used to return the value.

Dictionary get() Method Syntax

The dictionary get() method has the following syntax.

DICT.get(KEY,VALUE)
  • DICT is the dictionary the get() method will run.
  • KEY is the key we are looking for its value. The KEY is required for the get() method.
  • If the specified key is not found the provided VALUE will be returned. The VALUE parameter is optional.

Dictionary get() Method Example

Let's make some examples in order to understand the get() method of the dictionary data type. First, we will create a dictionary which is named fruits and items contains fruit names as key and counts for value.

fruits = { "apple":12 , "banana":5 , "tomato":7 }


count = fruits.get("apple")
print(count)


count = fruits.get("tomato")
print(count)

Now make an example where the specified key does not exist in the given dictionary. We will provide the VALUE parameter and if the specified key does not exist it will be returned. For this scenario, we will look for non-existing fruits, and as it doesn't exist 0 will be returned as value.

fruits = { "apple":12 , "banana":5 , "tomato":7 }


count = fruits.get("grape")
print(count)


count = fruits.get("grape",0)
print(count)

We can also use the get() method with nested dictionaries where an item in a dictionary is a dictionary too. Or it can be a different data type but in this example, we will example the nested dictionaries.

fruits = { "apple":{ "color":"red" , "count":12} , "banana":5 , "tomato":7 }


apple= fruits.get("apple")

color = apple.get("color")

count = apple.get("count")

print(color)

print(count)

In this example first we will get the "apple" item value which is dictionary too which contains "color" and "count" keys. Then we get the "color" and "count" values.

Leave a Comment