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

Tutorial Básico do Python

Controle de Fluxo do Python

Funções do Python

Tipos de Dados do Python

Operações de Arquivos do Python

Objetos e Classes do Python

Data e Hora do Python

Conhecimento Avançado do Python

Manual de Referência do Python

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

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 return value. The default value is None.

get() return value

get() method returns:

  • If the key is in the dictionary, 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 dictionaries?

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

When running this 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 this 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