English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python dictionary get() usage and example

Python dictionary methods

If the key is in the dictionary, the get() method returns the value of the specified key.

The syntax of get() is:

dict.get(key[, value])

get() parameters

The get() method can use up to two parameters:

  • key -The key to be searched in the dictionary

  • value(Optional)-If the key is not found, then the value is returned. The default value is None.

get() return value

get() method returns:

  • If the key is in the dictionary, then the value of the key is specified.

  • None - If the key is not found and no value is specified.

  • value - If the key is not found and a value is specified.

Example1How to use get() in the dictionary?

person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
# No value provided
print('Salary: ', person.get('salary'))
# Provide a value
print('Salary: ', person.get('salary', 0.0))

When running the program, the output is:

Name: Phill
Age:  22
Salary: None
Salary: 0.0

Python get() method and dict [key] element access

If the key lacks the get() method, the default value is returned.

However, if the key is not found when using dict[key], a KeyError exception will be raised.

print('Salary: ', person.get('salary'))
print(person['salary'])

When running the program, the output is:

Traceback (most recent call last):
  File '...', line 1, in <module>
    print('Salary: ', person.get('salary'))
NameError: name 'person' is not defined

Python dictionary methods