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

tutoriel de base Python

contrôle de flux Python

Fonctions en Python

Types de données en Python

opérations de fichiers Python

objets et classes Python

date et heure Python

connaissances avancées Python

manuel de référence Python

Usage and examples of Python dictionary get()

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, the value is returned. 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 a 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