Javatpoint Logo
Javatpoint Logo

Python Dictionary setdefault() Method

Python setdefault() method is used to set default value to the key. It returns value, if the key is present. Otherwise it insert key with the default value. Default value for the key is None.

Signature of this method is given below.

Signature

Parameters

key: key to be searched.

default: This value to be returned, if the key is not found.

Return

It returns a value, if the key is present. Otherwise None or default value.

Let's see some examples of setdefault() method to understand it's functionality.

Python Dictionary setdefault() Method Example 1

A simple example, if key is present, it returns associated value.

Output:

default 2500
{'B,Tech': 400000, 'BA': 2500, 'B.COM': 50000}

Python Dictionary setdefault() Method Example 2

If neither key nor default value is present, it returns None. See the following example.

Output:

default None
{'B,Tech': 400000, 'BA': 2500, 'B.COM': 50000, 'BCA': None}

Python Dictionary setdefault() Method Example 3

If key is not present but default value is set, it returns default value. See an example.

Output:

default 100000
{'B,Tech': 400000, 'BA': 2500, 'B.COM': 50000, 'BCA': 100000}

Next TopicPython Dictionary




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA