In this Python Dictionary tutorial, you will learn what get() method of dictionary dict class does, its syntax, and how to use this method to get the value for a given key in the dictionary, with example programs.

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.

Syntax

The syntax of dict.get() is

</>
Copy
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.

Examples (3)

In the following examples, we cover different scenarios like how to get the value of a key that is present in the dictionary, what does dict.get() do if the key is not present, and how to return a default value if key is not present using default parameter.

1. Get value of a key in dictionary

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

</>
Copy
myDictionary = {'a': 58, 'b': 61, 'c': 39}
value = myDictionary.get('b')
print(value)

Program Output

61

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

2. dict.get() with default parameter specified

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

</>
Copy
myDictionary = {'a': 58, 'b': 61, 'c': 39}
value = myDictionary.get('m', 0)
print(value)

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.

3. dict.get(key) for a key that is not present in the dictionary

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

</>
Copy
myDictionary = {'a': 58, 'b': 61, 'c': 39}
value = myDictionary.get('m')
print(value)

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().