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, else default.

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 Example

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

Example: Print the value for key ‘name’

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

get() Method Scenarios

The return value of the method depends on input parameters. Here are three scenarios for different return values.

Key Present

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

Example:

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

Default value is ignored if key is present

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

Key Absent, Default Specified

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

Example:

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

Key Absent, Default Not Specified

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

Example:

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

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.

Example:

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