Easy Tutorial
❮ Ref Set Add Python Install ❯

Python3 Dictionary setdefault() Method

Python3 Dictionary


Description

The Python dictionary setdefault() method is similar to the get() method. If the key does not exist in the dictionary, it will add the key and set its value to a default value.

Syntax

The syntax for the setdefault() method is:

dict.setdefault(key, default=None)

Parameters

Return Value

If the key is in the dictionary, it returns the corresponding value. If the key is not in the dictionary, it inserts the key with the default value and returns the default value. The default value is None by default.

Example

The following example demonstrates the use of the setdefault() method:

#!/usr/bin/python3

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

print("Value of Age key: %s" % tinydict.setdefault('Age', None))
print("Value of Sex key: %s" % tinydict.setdefault('Sex', None))
print("New dictionary:", tinydict)

The output of the above example is:

Value of Age key: 7
Value of Sex key: None
New dictionary: {'Age': 7, 'Name': 'tutorialpro', 'Sex': None}

Python3 Dictionary

❮ Ref Set Add Python Install ❯