Easy Tutorial
❮ Python File Isatty Python String Find ❯

Python3 Dictionary get() Method

Python3 Dictionary


Description

The Python dictionary get() function returns the value for the specified key.

Syntax

The syntax for the get() method is:

dict.get(key[, value])

Parameters

Return Value

Returns the value for the specified key, or None or the set default value if the key is not in the dictionary.

Example

The following example demonstrates the usage of the get() function:

#!/usr/bin/python

tinydict = {'Name': 'tutorialpro', 'Age': 27}

print("Age : ", tinydict.get('Age'))

# Sex is not set, and no default value is provided, outputs None
print("Sex : ", tinydict.get('Sex'))

# Salary is not set, outputs the default value 0.0
print('Salary: ', tinydict.get('Salary', 0.0))

The output of the above example is:

Age : 27
Sex : None
Salary: 0.0

get() Method vs dict[key] Access Difference

The get(key) method can return the default value None or the set default value if the key is not in the dictionary.

dict[key] will trigger a KeyError exception if the key is not in the dictionary.

Example

>>> tutorialpro = {}
>>> print('URL: ', tutorialpro.get('url'))     # Returns None
URL:  None

>>> print(tutorialpro['url'])     # Triggers KeyError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'url'
>>>

Nested Dictionary Usage

The get() method for nested dictionaries is used as follows:

#!/usr/bin/python

tinydict = {'tutorialpro' : {'url' : 'www.tutorialpro.org'}}

res = tinydict.get('tutorialpro', {}).get('url')
# Output result
print("tutorialpro url is : ", str(res))

The output of the above example is:

tutorialpro url is :  www.tutorialpro.org

Python3 Dictionary

❮ Python File Isatty Python String Find ❯