Python Dictionary get() Method

Returns the value for key if exists

Usage

The get() method returns the value for key if key is in the dictionary.

You can also specify the default parameter that will be returned if the specified key is not found. If default is not specified, it returns None. Therefore, this method never raises a KeyError.

It’s an easy way of getting the value of a key from a dictionary without raising an error.

Syntax

dictionary.get(key,default)

Python dictionary get() method parameters
ParameterConditionDescription
keyRequiredAny key you want to search for
defaultOptionalA value to return if the specified key is not found.
Default value is None.

Basic Examples

get() method is generally used to get the value for the specific key.

D = {'name': 'Bob', 'age': 25}
print(D.get('name'))
# Prints Bob

If key is not in the dictionary, the method returns None.

D = {'name': 'Bob', 'age': 25}
print(D.get('job'))
# Prints None

Sometimes you want a value other than None to be returned, in which case specify the default parameter.

The default Parameter

If key is in the dictionary, the method returns the value for key (no matter what you pass in as default).

D = {'name': 'Bob', 'age': 25, 'job': 'Manager'}
print(D.get('job', 'Developer'))
# Prints Manager

But if key is not in the dictionary, the method returns specified default.

D = {'name': 'Bob', 'age': 25}
print(D.get('job','Developer'))
# Prints Developer

get() Method vs Dictionary Indexing

The get() method is similar to indexing a dictionary by key in that it returns the value for the specified key. However, it never raises a KeyError, if you refer to a key that is not in the dictionary.

# key present
D = {'name': 'Bob', 'age': 25}
print(D['name'])
# Prints Bob
print(D.get('name'))
# Prints Bob
# key absent
D = {'name': 'Bob', 'age': 25}
print(D['job'])
# Triggers KeyError: 'job'
print(D.get('job'))
# Prints None