Python Dictionary get()

Python Dictionary get(key[, default]) method returns the value for the key if the key is present, else returns default (if provided) value. If key is not present in the dictionary and default value is not provided, get() returns None.

In this tutorial, we will learn the syntax of dict.get() method and go through examples covering different scenarios for the arguments that we pass to get() method.

Syntax – dict.get()

The syntax of dict.get() is

dict.get(key[, default])

where

key is the key we want to lookup in the dictionary.

default is the value we want get() to return when there no match for the key in dictionary. default value is optional.

Example 1 – Python dict.get(key)

In this example, we will get the value for key "b" in the dictionary. The key "b" is present in the dictionary. No default value will be given as second argument.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
value = dictionary.get('b')
print(value)
Try Online

Program Output

61

As the key is present in the dictionary, get() method returned the corresponding value.

Example 2 – Python dict.get(key, default)

In this example, we will get the value for key "m" in the dictionary. The key "m" is not present in the dictionary. Default value of 0 is given as second argument.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
value = dictionary.get('m', 0)
print(value)
Try Online

Program Output

0

As the key is not present in the dictionary, and default value is given to the method, get() returns the default value.

Example 3 – Python dict.get(key)

In this example, we will get the value for key "m" in the dictionary. The key "m" is not present in the dictionary. No default value will be given as second argument.

Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39}
value = dictionary.get('m')
print(value)
Try Online

Program Output

None

As the key is not present in the dictionary and no default value is provided to get() method, the method returns None.

Conclusion

In this Python Tutorial, we learned about Python Dictionary method dict.get(). We have gone through the syntax of get(), and its usage with example programs.