Python Dictionary – setdefault() method

It is a method in python that returns the value of the specified key from the dictionary, if key is absent returns the value provided in the arguments.

Syntax:
dictionary.setdefault(key, value_if_key_absent)

Also Read: Python Dictionary – has_key() method

Example 1:

# Python code to understand setdefault() method in dictionary
# www.codewindow.in

s = {0:"CodeWindow", 1:"India", 2:"News"}
x = s.setdefault(1, "Tech")
print(x)

Output:

India

Explanation:
Here it returned the value (India) of the specified key (0).

Example 2:

# Python code to understand setdefault() method in dictionary
# www.codewindow.in

s = {"site":"CodeWindow", "country":"India", "type":"News", "platform":"IT"}
x = s.setdefault("origin", "Bengal")
print(x)

Output:

Bengal

Explanation:
Here it returned “Bengal” because the key “origin” is absent in the dictionary. Hence it returned the value provided in the arguments.


You Missed

Also Checkout