Python dictionary Method - get()

The get() method is a built-in dictionary method in Python that returns the value associated with a specified key in the dictionary. If the key is not present in the dictionary, the method returns a default value specified as the second argument. If no default value is specified and the key is not present, the method returns None.

Here's the syntax for the get() method:

re‮t ref‬o:theitroad.com
value = my_dict.get(key, default=None)

Here, key is the key to look up in the dictionary, and default is the default value to return if the key is not present. If default is not specified, the default value is None.

Here's an example:

# create a dictionary
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}

# get the value associated with the key 'banana'
banana_count = my_dict.get('banana')

# get the value associated with the key 'orange', with default value 0
orange_count = my_dict.get('orange', 0)

# print the results
print(banana_count)
print(orange_count)

Output:

2
0

In this example, we create a dictionary my_dict with three key-value pairs. We then use the get() method to retrieve the value associated with the key 'banana', which is 2. We also use the get() method to retrieve the value associated with the key 'orange', which is not present in the dictionary. Since we specify a default value of 0, the method returns 0. If we had not specified a default value, the method would have returned None.

The get() method is useful when you need to retrieve a value from a dictionary and handle the case when the key is not present. It can be more convenient than using the square bracket syntax to look up a key, because it avoids raising a KeyError if the key is not present.