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

Tutoriales Básicos de Python

Control de Flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de Archivos de Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de 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() is:

dict.get(key[, value])

get() parameters

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

  • key -The key to search for 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 does get() work 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